11.2. Using an IndexReader

Queries in Lucene are executed on an IndexReader. Hibernate Search might cache index readers to maximize performance, or provide other efficient strategies to retrieve an updated IndexReader minimizing IO operations. Your code can access these cached resources, but you have to follow some "good citizen" rules.

Example 11.2. Accessing an IndexReader

IndexReader reader = searchFactory.getIndexReaderAccessor().open(Order.class);
try {
   //perform read-only operations on the reader
}
finally {
   searchFactory.getIndexReaderAccessor().close(reader);
}
In this example the SearchFactory figures out which indexes are needed to query this entity (considering a Sharding strategy). Using the configured ReaderProvider (described in Section 4.3, “Reader Strategies”) on each index, it returns a compound IndexReader on top of all involved indexes. Because this IndexReader is shared amongst several clients, you must adhere to the following rules:
  • Never call indexReader.close(), instead use readerProvider.closeReader(reader) when necessary, preferably in a finally block.
  • Don't use this IndexReader for modification operations (it's a readonly IndexReader, you would get an exception).
Aside from those rules, you can use the IndexReader freely, especially to do native Lucene queries. Using the shared IndexReaders will make most queries more efficient than by opening one directly from - for example - the filesystem.
As an alternative to the method open(Class... types) you can use open(String... indexNames); in this case you pass in one or more index names; using this strategy you can also select a subset of the indexes for any indexed type if sharding is used.

Example 11.3. Accessing an IndexReader by index names

IndexReader reader = searchFactory.getIndexReaderAccessor().open("Products.1", "Products.3");