题
我刚刚开始将 Hibernate Search 与我的 Hibernate 应用程序集成。每次启动服务器时,都会使用 Hibernate Session 对数据进行索引。
FullTextSession fullTextSession = Search.getFullTextSession(session);
Transaction tx = fullTextSession.beginTransaction();
List books = session.createQuery("from Book as book").list();
for (Book book : books) {
fullTextSession.index(book);
}
tx.commit(); //index is written at commit time
非常尴尬,服务器需要10分钟才能启动。我这样做的方式正确吗?
我编写了一个调度程序,它将定期更新索引。这会自动更新现有索引条目,还是创建重复索引?
解决方案
作为休眠搜索导向,部分3.6.1中所详述,如果正在使用注释(到现在为止的默认值),其上存储启动索引听众默认注册:
休眠搜索启用出的 使用Hibernate批注框时 或休眠的EntityManager。如果, 由于某种原因,你需要禁用它, 组 hibernate.search.autoregister_listeners 为假。
关于如何用手打开它们的示例:
hibConfiguration.setListener("post-update", new FullTextIndexEventListener());
hibConfiguration.setListener("post-insert", new FullTextIndexEventListener());
hibConfiguration.setListener("post-delete", new FullTextIndexEventListener());
所有你需要做的是注释要与被索引的实体
@Indexed(index = "fulltext")
注释,然后执行上的字段细粒度注释,按照用户手册中详细描述。
所以,你应该既不存放时用手工启动索引,既不重新开张索引whae在应用程序启动,除非你有启用索引之前已经存储的实体。
您可以得到性能问题,当你存储的对象,说有一个“附件”等你索引,正在被存储在实体交易的同一范围。在这里看到:
用于解决该问题的解决方案。
其他提示
如果您使用 FSDirectoryProvider(默认),Lucene 索引将保留在磁盘上。这意味着无需在启动时建立索引。如果您有现有数据库,您当然希望使用 fullTextSession.index() 功能创建初始索引。但是,这不应该在应用程序启动时进行。考虑公开某种触发 URL 或管理界面。一旦有了初始索引,我建议使用自动索引。这意味着如果书籍被创建/更新/删除,Lucene 索引会自动更新。默认情况下还应启用自动索引。
我建议您参考在线手册中的自动和手动索引部分 - http://docs.jboss.org/hibernate/stable/search/reference/en/html_single
——哈代
我目前使用Hibernate Search的使用JPA自动索引和它的作品真的很好。最初创建索引时你可以拨打以下内容:
FullTextEntityManager fullTextEntityManager =
Search.getFullTextEntityManager(entityManager);
try {
fullTextEntityManager.createIndexer().startAndWait();
} catch (InterruptedException e) {
// Exception handling
}
其中 “的EntityManager” 只是一个javax.persistence.EntityManager。上述将索引的所有字段标有@Field为所有的实体标记为@Indexed。
然后,只要你做你的更新等,通过实体管理器的索引自动更新。然后,您可以搜索按通常但一定要重新创建每个搜索的EntityManager(可以使用的EntityManagerFactory这样做)。