Friday, June 1, 2012

Using Lucene With Hibernate

Lucene is a powerful java-based full-text search engine. If you are using Hibernate, it is possible to use Lucene easily and transparently with Hibernate taking care of telling Lucene to update the indexes etc. Lucene searches can also be wrapped in Hibernate searches.

To use Lucene with Hibernate, download Hibernate Search: http://www.hibernate.org/subprojects/search.html

A copy of the Lucene libraries is also provided.

Setup
By default, Hibernate Search will be enabled once Hibernate detects that it is on the classpath.

Any additional configuration can be done in the hibernate.cfg.xml file. E.g.

<property name="hibernate.search.default.directory_provider">filesystem</property>
<property name="hibernate.search.default.indexBase">/var/lucene/indexes</property>

These tell Lucene to use the filesystem based index directory and the folder to store the indexes.

Searchable Fields
To tell Hibernate to auto-index classes & fields, mark classes with the annotation "@Indexed", and fields with "@Field", and the primary key as "@DocumentId".

All subsequent updates to the table will be indexed (Note: prior entries, if any, will have to be manually indexed).

Manual Indexing
A one-time manual indexing can be done by calling:
FullTextSession fts = Search.getFullTextSession(session);
fts.createIndexer().startAndWait();

Query
FullTextSession fts = Search.getFullTextSession(session);
QueryBuilder qb = fts.getSearchFactory().buildQueryBuilder().forEntity(Book.class).get();
org.apache.lucene.search.Query luceneSearchQuery = qb.keyword().onFields("author").matching(searchParam).createQuery();
FullTextQuery hibernateQuery = fts.createFullTextQuery(luceneSearchQuery);
List<Book> results = hibernateQuery.list(); // same paradigm as Hibernate querying

References
Hibernate Search Manual: http://docs.jboss.org/hibernate/stable/search/reference/en-US/html/index.html

No comments:

Post a Comment