Getting Start
1.1系统配置要求
java runtime | JDK或JRE5以上版本 |
Hibernate Search | hibernate-search-3.4.0.Final.jar及其所需依赖。可通过Jboss Maven仓库下载(http://repository.jboss.org/ nexus/content/groups/public-jboss/ ) |
Hibernate Core | 3.4版本的Hibernate Search与3.6版本的Hibernate Core测试良好 |
JPA2 | 虽然Hinbernate Search没有用到JPA,但Hibernate的持久化必须要用到JPA(如@Entity等) |
1.2通过Maven配置依赖
1.2.1添加Jboss Maven仓库
<settings> ... <profiles> ... <profile> <id>jboss-public-repository</id> <repositories> <repository> <id>jboss-public-repository-group</id> <name>JBoss Public Maven Repository Group</name> <url>https://repository.jboss.org/nexus/content/groups/public-jboss/</url> <layout>default</layout> <releases> <enabled>true</enabled> <updatePolicy>never</updatePolicy> </releases> <snapshots> <enabled>true</enabled> <updatePolicy>never</updatePolicy> </snapshots> </repository> </repositories> <pluginRepositories> <pluginRepository> <id>jboss-public-repository-group</id> <name>JBoss Public Maven Repository Group</name> <url>https://repository.jboss.org/nexus/content/groups/public-jboss/</url> <layout>default</layout> <releases> <enabled>true</enabled> <updatePolicy>never</updatePolicy> </releases> <snapshots> <enabled>true</enabled> <updatePolicy>never</updatePolicy> </snapshots> </pluginRepository> </pluginRepositories> </profile> </profiles> <activeProfiles> <activeProfile>jboss-public-repository</activeProfile> </activeProfiles> ... </setting>
1.2.2在Maven应用中添加依赖
<!--实际上只需要hibernate-search就足够了,因为maven会根据传递性依赖原则添加其他依赖,像hibnerate-core等等--> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-search</artifactId> <version>3.4.0.Final</version> </dependency> <!--当需要用到hibernate-entitymanager时添加--> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>3.6.3.Final</version> </dependency>
1.3hibernate.cfg.xml或persistence.xml配置
... <property name="hibernate.search.default.directory_provider" value="filesystem"/> <property name="hibernate.search.default.indexBase" value="/var/lucene/indexes"/> ...
属性hibernate.search.default.directory_provider告诉hibernate使用哪个DirectoryProvider实现。在Apache Lucene中有一个概念Directory来保存Index Files。Hibernate通过DirectoryProvider来初始化和配置一个Lucene Directory实例。在本例中,我们使用一个能把Index Files保存在file system中的DirectoryProvider。当Index Files保存在file system中时,我们可以通过Luke工具实时查看Lucene索引文件。除了DirectoryProvider外,还需要告诉hibernate索引文件保存在哪个具体的目录中,这通过hibernate.search.default.indexBase属性来配置。
我们假设有两个由hibernate持久的类文件example.Book和example.Author,并且想要为该应用添加全文搜索能力。请看下面样例:
package example;
...
@Entity
@Indexed
public class Book {
@Id
@GeneratedValue
private Integer id;
@Field(index=Index.TOKENIZED, store=Store.NO)
private String title;
@Field(index=Index.TOKENIZED, store=Store.NO)
private String subtitle;
@IndexedEmbedded
@ManyToMany
private Set<Author> authors = new HashSet<Author>();
@Field(index = Index.UN_TOKENIZED, store = Store.YES)
@DateBridge(resolution = Resolution.DAY)
private Date publicationDate;
public Book() {
}
// standard getters/setters follow here
...
}
package example;
...
@Entity
public class Author {
@Id
@GeneratedValue
private Integer id;
@Field(index=Index.TOKENIZED, store=Store.NO)
private String name;
public Author() {
}
// standard getters/setters follow here
...
}
@Indexed:标注Book是可索引的。
@DocumentId:主键标注,当有@Id时可省略
@Field:标注哪些域是可搜索的。其中index=Index.TOKENIZED参数说明可以通过Analyzer解析,store=Store.NO参数说明是否在索引文件中保存该域的值。
Note :无论store=Store.NO还是store=Store.YES都不会影响最终的搜索能力。store.YES的作用是可以在搜索后可以直接从索引中获取域的完整值。在hibernate中,如果store=Store.NO,搜索结果中,域的值是通过数据库中获取,如果store=Store.YES,域的值是直接从索引文档中获取。
@DateBridge:因为Lucene只支持纯字符串的索引(Lucene2.9后支持数值索引),基于这样的原因,hibernate必须把Date类型的值转换成字符串
@IndexedEmbedded:该注解用于建立关联实体的索引。这是必须的,因为Lucene的索引文档是一种平整的数据结构,它不像数据库那样支持对象关联。为了确保author的名字可搜索,必须把author的名字作为Book索引文档的一个域。
1.4建立索引
Hibernate会在进行实体持久化,更新,删除操作时自动地建立索引。但是,你还必须为已经存在于数据库中的数据建立索引。下面的例子基于上面的配置和持久化类,展示了如何进行初始化索引。
//使用Hibernate Session初始化索引
FullTextSession fullTextSession = Search.getFullTextSession(session);
fullTextSession.createIndexer().startAndWait();
//使用JPA初始化索引
EntityManager em = entityManagerFactory.createEntityManager();
FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(em);
fullTextEntityManager.createIndexer().startAndWait();
运行了上面的代码后,你会在/var/lucene/indexes/中找到example.Book索引文件,你可能使用Luke查看索引文件,这可以帮助你更好地理解Hibernate Search。
1.5.建立搜索
有两种方法可以建立搜索,一种是直接使用Lucene的API,另一种是使用Hibernate Search query DSL。后者可以被包装成org.hibernate.Query,从而可以使用Hibernate API的机能。
通过Hibernate Session创建和运行搜索
FullTextSession fullTextSession = Search.getFullTextSession(session);
Transaction tx = fullTextSession.beginTransaction();
// create native Lucene query unsing the query DSL
// alternatively you can write the Lucene query using the Lucene query parser
// or the Lucene programmatic API. The Hibernate Search DSL is recommended though
QueryBuilder qb = fullTextSession.getSearchFactory()
.buildQueryBuilder().forEntity( Book.class ).get();
org.apache.lucene.search.Query query = qb
.keyword()
.onFields("title", "subtitle", "authors.name", "publicationDate")
.matching("Java rocks!")
.createQuery();
// wrap Lucene query in a org.hibernate.Query
org.hibernate.Query hibQuery =
fullTextSession.createFullTextQuery(query, Book.class);
// execute search
List result = hibQuery.list();
tx.commit();
session.close();
通过JPA创建和运行搜索
EntityManager em = entityManagerFactory.createEntityManager();
FullTextEntityManager fullTextEntityManager =
org.hibernate.search.jpa.Search.getFullTextEntityManager(em);
em.getTransaction().begin();
// create native Lucene query unsing the query DSL
// alternatively you can write the Lucene query using the Lucene query parser
// or the Lucene programmatic API. The Hibernate Search DSL is recommended though
QueryBuilder qb = fullTextSession.getSearchFactory()
.buildQueryBuilder().forEntity( Book.class ).get();
org.apache.lucene.search.Query query = qb
.keyword()
.onFields("title", "subtitle", "authors.name", "publicationDate")
.matching("Java rocks!");
.createQuery();
// wrap Lucene query in a javax.persistence.Query
javax.persistence.Query persistenceQuery =
fullTextEntityManager.createFullTextQuery(query, Book.class);
// execute search
List result = persistenceQuery.getResultList();
em.getTransaction().commit();
em.close();
1.6 Analyzer(解析器)
Analyzer指定了按怎么样的规则去分词,比如词干分析("refactor", "refactors", "refactored" and "refactoring"都会是被认为是同一个词),是否去掉一些stop words(a,an,the)等等。Hibernate提供了几种方式去配置analyzer。
- 在配置文件中配置 hibernate.search.analyzer属性。这里配置的analyzer是默认的解析器。
- 在类级别中添加注解@Analyzer
- 在域级别添加注解@Analyzer
在@Analyzer注解可以指定完全限定名,也可以是一个由@AnalyzerDef定义的analyzer的引用名。后一种方式会利用Solr Analyzer Framework的工厂方法。你可以通过查看Solr JavaDoc 或查看Solr Wiki相关段落找到更多可用的工厂方法。
在下面的例子中,StandardTokenizerFactory首先经过两个过滤器工厂(filter factories)过滤:LowerCaseFilterFactory 和 SnowballPorterFilterFactory。StandardTokenizerFactory通过标点与‘-’来划分词语,但保留像email,internet地址的完整性。LowerCaseFilterFactory把字母统一变成小写,而SnowballPorterFilterFactory处理指定语言的词干分析。
一般地,使用Solr Framework需要先定义一个tokenizer,之后是任意数量的filter。
使用@AnalyzerDef和Solr Framework定义和使用Analyzer
@Entity
@Indexed
@AnalyzerDef(name = "customanalyzer",
tokenizer = @TokenizerDef(factory = StandardTokenizerFactory.class),
filters = {
@TokenFilterDef(factory = LowerCaseFilterFactory.class),
@TokenFilterDef(factory = SnowballPorterFilterFactory.class, params = {
@Parameter(name = "language", value = "English")
})
})
public class Book {
@Id
@GeneratedValue
@DocumentId
private Integer id;
@Field(index=Index.TOKENIZED, store=Store.NO)
@Analyzer(definition = "customanalyzer")
private String title;
@Field(index=Index.TOKENIZED, store=Store.NO)
@Analyzer(definition = "customanalyzer")
private String subtitle;
@IndexedEmbedded
@ManyToMany
private Set<Author> authors = new HashSet<Author>();
@Field(index = Index.UN_TOKENIZED, store = Store.YES)
@DateBridge(resolution = Resolution.DAY)
private Date publicationDate;
public Book() {
}
// standard getters/setters follow here
...
}