Hibernate Search Reference
Hibernate Search Reference
Apache Lucene™
Integration
Reference Guide
3.2.1.Final
Preface ............................................................................................................................ vii
1. Getting started ............................................................................................................. 1
1.1. System Requirements ......................................................................................... 1
1.2. Using Maven ...................................................................................................... 1
1.3. Configuration ...................................................................................................... 3
1.4. Indexing ............................................................................................................. 7
1.5. Searching ........................................................................................................... 8
1.6. Analyzer ............................................................................................................. 9
1.7. What's next ...................................................................................................... 11
2. Architecture ............................................................................................................... 13
2.1. Overview .......................................................................................................... 13
2.2. Back end .......................................................................................................... 14
2.2.1. Back end types ...................................................................................... 14
2.2.2. Work execution ...................................................................................... 16
2.3. Reader strategy ................................................................................................ 16
2.3.1. Shared .................................................................................................. 16
2.3.2. Not-shared ............................................................................................. 17
2.3.3. Custom .................................................................................................. 17
3. Configuration ............................................................................................................. 19
3.1. Directory configuration ....................................................................................... 19
3.2. Sharding indexes .............................................................................................. 21
3.3. Sharing indexes (two entities into the same directory) ......................................... 23
3.4. Worker configuration ......................................................................................... 24
3.5. JMS Master/Slave configuration ......................................................................... 25
3.5.1. Slave nodes ........................................................................................... 25
3.5.2. Master node .......................................................................................... 26
3.6. JGroups Master/Slave configuration ................................................................... 28
3.6.1. Slave nodes ........................................................................................... 28
3.6.2. Master node .......................................................................................... 28
3.6.3. JGroups channel configuration ................................................................ 28
3.7. Reader strategy configuration ............................................................................ 30
3.8. Enabling Hibernate Search and automatic indexing ............................................. 30
3.8.1. Enabling Hibernate Search ..................................................................... 30
3.8.2. Automatic indexing ................................................................................. 31
3.9. Tuning Lucene indexing performance ................................................................. 32
3.10. LockFactory configuration ................................................................................ 36
3.11. Exception Handling Configuration ..................................................................... 38
4. Mapping entities to the index structure ..................................................................... 41
4.1. Mapping an entity ............................................................................................. 41
4.1.1. Basic mapping ....................................................................................... 41
4.1.2. Mapping properties multiple times ........................................................... 43
4.1.3. Embedded and associated objects .......................................................... 44
4.1.4. Boost factor ........................................................................................... 48
4.1.5. Dynamic boost factor .............................................................................. 49
iii
Hibernate Search
iv
8.3. Using an IndexReader ..................................................................................... 107
8.4. Customizing Lucene's scoring formula .............................................................. 108
v
vi
Preface
Full text search engines like Apache Lucene are very powerful technologies to add efficient
free text search capabilities to applications. However, Lucene suffers several mismatches when
dealing with object domain model. Amongst other things indexes have to be kept up to date and
mismatches between index structure and domain model as well as query mismatches have to
be avoided.
Hibernate Search addresses these shortcomings - it indexes your domain model with the help
of a few annotations, takes care of database/index synchronization and brings back regular
managed objects from free text queries. To achieve this Hibernate Search is combining the power
of Hibernate [http://www.hibernate.org] and Apache Lucene [http://lucene.apache.org].
vii
viii
Chapter 1.
Getting started
Welcome to Hibernate Search. The following chapter will guide you through the initial steps
required to integrate Hibernate Search into an existing Hibernate enabled application. In case you
are a Hibernate new timer we recommend you start here [http://hibernate.org/152.html].
You can download all dependencies from the Hibernate download site.
1
Chapter 1. Getting started
your Maven settings.xml file (see also Maven Getting Started [http://community.jboss.org/
wiki/MavenGettingStarted-Users]):
<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/</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/</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>
2
Configuration
<activeProfile>jboss-public-repository</activeProfile>
</activeProfiles>
...
</settings>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-search</artifactId>
<version>3.2.1.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>3.5.0-Final</version>
</dependency>
Only the hibernate-search dependency is mandatory, because it contains together with its
required transitive dependencies all required classes needed to use Hibernate Search. hibernate-
entitymanager is only required if you want to use Hibernate Search in conjunction with JPA.
Note
1.3. Configuration
Once you have downloaded and added all required dependencies to your application you have to
add a couple of properties to your hibernate configuration file. If you are using Hibernate directly
this can be done in hibernate.properties or hibernate.cfg.xml. If you are using Hibernate
via JPA you can also add the properties to persistence.xml. The good news is that for standard
use most properties offer a sensible default. An example persistence.xml configuration could
look like this:
3
Chapter 1. Getting started
...
<property name="hibernate.search.default.directory_provider"
value="org.hibernate.search.store.FSDirectoryProvider"/>
<property name="hibernate.search.default.indexBase"
value="/var/lucene/indexes"/>
...
First you have to tell Hibernate Search which DirectoryProvider to use. This can be achieved
by setting the hibernate.search.default.directory_provider property. Apache Lucene has
the notion of a Directory to store the index files. Hibernate Search handles the initialization
and configuration of a Lucene Directory instance via a DirectoryProvider. In this tutorial
we will use a subclass of DirectoryProvider called FSDirectoryProvider. This will give
us the ability to physically inspect the Lucene indexes created by Hibernate Search (eg
via Luke [http://www.getopt.org/luke/]). Once you have a working configuration you can start
experimenting with other directory providers (see Section 3.1, “Directory configuration”). Next
to the directory provider you also have to specify the default root directory for all indexes via
hibernate.search.default.indexBase.
Lets assume that your application contains the Hibernate managed classes example.Book and
example.Author and you want to add free text search capabilities to your application in order to
search the books contained in your database.
Example 1.4. Example entities Book and Author before adding Hibernate
Search specific annotations
package example;
...
@Entity
public class Book {
@Id
@GeneratedValue
private Integer id;
@ManyToMany
private Set<Author> authors = new HashSet<Author>();
4
Configuration
public Book() {}
package example;
...
@Entity
public class Author {
@Id
@GeneratedValue
private Integer id;
public Author() {}
To achieve this you have to add a few annotations to the Book and Author class. The first
annotation @Indexed marks Book as indexable. By design Hibernate Search needs to store an
untokenized id in the index to ensure index unicity for a given entity. @DocumentId marks the
property to use for this purpose and is in most cases the same as the database primary key. In
fact since the 3.1.0 release of Hibernate Search @DocumentId is optional in the case where an
@Id annotation exists.
Next you have to mark the fields you want to make searchable. Let's start with title and subtitle
and annotate both with @Field. The parameter index=Index.TOKENIZED will ensure that the
text will be tokenized using the default Lucene analyzer. Usually, tokenizing means chunking a
sentence into individual words and potentially excluding common words like 'a' or 'the'. We
will talk more about analyzers a little later on. The second parameter we specify within @Field,
store=Store.NO, ensures that the actual data will not be stored in the index. Whether this data
is stored in the index or not has nothing to do with the ability to search for it. From Lucene's
perspective it is not necessary to keep the data once the index is created. The benefit of storing
it is the ability to retrieve it via projections (Section 5.1.2.5, “Projection”).
Without projections, Hibernate Search will per default execute a Lucene query in order to find the
database identifiers of the entities matching the query critera and use these identifiers to retrieve
managed objects from the database. The decision for or against projection has to be made on a
5
Chapter 1. Getting started
case to case basis. The default behaviour - Store.NO - is recommended since it returns managed
objects whereas projections only return object arrays.
After this short look under the hood let's go back to annotating the Book class. Another annotation
we have not yet discussed is @DateBridge. This annotation is one of the built-in field bridges in
Hibernate Search. The Lucene index is purely string based. For this reason Hibernate Search must
convert the data types of the indexed fields to strings and vice versa. A range of predefined bridges
are provided, including the DateBridge which will convert a java.util.Date into a String with
the specified resolution. For more details see Section 4.2, “Property/Field Bridge”.
This leaves us with @IndexedEmbedded. This annotation is used to index associated entities
(@ManyToMany, @*ToOne and @Embedded) as part of the owning entity. This is needed since a
Lucene index document is a flat data structure which does not know anything about object
relations. To ensure that the authors' name wil be searchable you have to make sure that the
names are indexed as part of the book itself. On top of @IndexedEmbedded you will also have to
mark all fields of the associated entity you want to have included in the index with @Indexed. For
more details see Section 4.1.3, “Embedded and associated objects”.
These settings should be sufficient for now. For more details on entity mapping refer to Section 4.1,
“Mapping an entity”.
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>();
public Book() {
6
Indexing
package example;
...
@Entity
public class Author {
@Id
@GeneratedValue
private Integer id;
@Field(index=Index.TOKENIZED, store=Store.NO)
private String name;
public Author() {
}
1.4. Indexing
Hibernate Search will transparently index every entity persisted, updated or removed through
Hibernate Core. However, you have to create an initial Lucene index for the data already present
in your database. Once you have added the above properties and annotations it is time to trigger
an initial batch index of your books. You can achieve this by using one of the following code
snippets (see also Section 6.3, “Rebuilding the whole Index”):
EntityManager em = entityManagerFactory.createEntityManager();
FullTextEntityManager fullTextEntityManager =
Search.getFullTextEntityManager(em);
7
Chapter 1. Getting started
fullTextEntityManager.createIndexer().startAndWait();
After executing the above code, you should be able to see a Lucene index under /var/lucene/
indexes/example.Book. Go ahead an inspect this index with Luke [http://www.getopt.org/luke/].
It will help you to understand how Hibernate Search works.
1.5. Searching
Now it is time to execute a first search. The general approach is to create a native Lucene query
and then wrap this query into a org.hibernate.Query in order to get all the functionality one is used
to from the Hibernate API. The following code will prepare a query against the indexed fields,
execute it and return a list of Books.
// execute search
List result = hibQuery.list();
tx.commit();
session.close();
EntityManager em = entityManagerFactory.createEntityManager();
FullTextEntityManager fullTextEntityManager =
org.hibernate.search.jpa.Search.getFullTextEntityManager(em);
em.getTransaction().begin();
8
Analyzer
// execute search
List result = persistenceQuery.getResultList();
em.getTransaction().commit();
em.close();
1.6. Analyzer
Let's make things a little more interesting now. Assume that one of your indexed book entities
has the title "Refactoring: Improving the Design of Existing Code" and you want to get hits for all
of the following queries: "refactor", "refactors", "refactored" and "refactoring". In Lucene this can
be achieved by choosing an analyzer class which applies word stemming during the indexing as
well as search process. Hibernate Search offers several ways to configure the analyzer to use
(see Section 4.1.6, “Analyzer”):
• Setting the hibernate.search.analyzer property in the configuration file. The specified class
will then be the default analyzer.
When using the @Analyzer annotation one can either specify the fully qualified classname of
the analyzer to use or one can refer to an analyzer definition defined by the @AnalyzerDef
annotation. In the latter case the Solr analyzer framework with its factories approach is
utilized. To find out more about the factory classes available you can either browse the
Solr JavaDoc or read the corresponding section on the Solr Wiki. [http://wiki.apache.org/solr/
AnalyzersTokenizersTokenFilters]
Generally, when using the Solr framework you have to start with a tokenizer followed by an
arbitrary number of filters.
9
Chapter 1. Getting started
Example 1.10. Using @AnalyzerDef and the Solr framework to define and use
an analyzer
package example;
...
@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>();
public Book() {
}
10
What's next
11
12
Chapter 2.
Architecture
2.1. Overview
Hibernate Search consists of an indexing component and an index search component. Both are
backed by Apache Lucene.
Each time an entity is inserted, updated or removed in/from the database, Hibernate Search keeps
track of this event (through the Hibernate event system) and schedules an index update. All the
index updates are handled without you having to use the Apache Lucene APIs (see Section 3.8,
“Enabling Hibernate Search and automatic indexing”).
Hibernate Search uses the Lucene index to search an entity and return a list of managed entities
saving you the tedious object to Lucene document mapping. The same persistence context is
shared between Hibernate and Hibernate Search. As a matter of fact, the FullTextSession
is built on top of the Hibernate Session. so that the application code can use the unified
org.hibernate.Query or javax.persistence.Query APIs exactly the way a HQL, JPA-QL or
native queries would do.
To be more efficient, Hibernate Search batches the write interactions with the Lucene index. There
is currently two types of batching depending on the expected scope. Outside a transaction, the
index update operation is executed right after the actual database operation. This scope is really
a no scoping setup and no batching is performed. However, it is recommended - for both your
database and Hibernate Search - to execute your operation in a transaction be it JDBC or JTA.
When in a transaction, the index update operation is scheduled for the transaction commit phase
and discarded in case of transaction rollback. The batching scope is the transaction. There are
two immediate benefits:
• Performance: Lucene indexing works better when operation are executed in batch.
• ACIDity: The work executed has the same scoping as the one executed by the database
transaction and is executed if and only if the transaction is committed. This is not ACID in the
strict sense of it, but ACID behavior is rarely useful for full text search indexes since they can
be rebuilt from the source at any time.
You can think of those two scopes (no scope vs transactional) as the equivalent of the (infamous)
autocommit vs transactional behavior. From a performance perspective, the in transaction mode is
recommended. The scoping choice is made transparently. Hibernate Search detects the presence
of a transaction and adjust the scoping.
13
Chapter 2. Architecture
Note
Hibernate Search works perfectly fine in the Hibernate / EntityManager long
conversation pattern aka. atomic conversation.
Note
Depending on user demand, additional scoping will be considered, the pluggability
mechanism being already in place.
2.2.1.1. Lucene
In this mode, all index update operations applied on a given node (JVM) will be executed to the
Lucene directories (through the directory providers) by the same node. This mode is typically used
in non clustered environment or in clustered environments where the directory store is shared.
This mode targets non clustered applications, or clustered applications where the Directory is
taking care of the locking strategy.
The main advantage is simplicity and immediate visibility of the changes in Lucene queries (a
requirement in some applications).
14
Back end types
2.2.1.2. JMS
All index update operations applied on a given node are sent to a JMS queue. A unique reader
will then process the queue and update the master index. The master index is then replicated on
a regular basis to the slave copies. This is known as the master/slaves pattern. The master is
the sole responsible for updating the Lucene index. The slaves can accept read as well as write
operations. However, they only process the read operation on their local index copy and delegate
the update operations to the master.
This mode targets clustered environments where throughput is critical, and index update delays
are affordable. Reliability is ensured by the JMS provider and by having the slaves working on
a local copy of the index.
2.2.1.3. JGroups
The JGroups based back end works similarly as the JMS one. Designed on the same master/
slave pattern, instead of JMS the JGroups toolkit is used as a replication mechanism. This back
end can be used as an alternative to JMS one when response time is still critical, but i.e. JNDI
service is not available.
15
Chapter 2. Architecture
Note
Hibernate Search is an extensible architecture. Feel free to drop ideas for other
third party back ends to [email protected].
The indexing work (done by the back end) can be executed synchronously with the transaction
commit (or update operation if out of transaction), or asynchronously.
2.2.2.1. Synchronous
This is the safe mode where the back end work is executed in concert with the transaction
commit. Under highly concurrent environment, this can lead to throughput limitations (due to the
Apache Lucene lock mechanism) and it can increase the system response time if the backend is
significantly slower than the transactional process and if a lot of IO operations are involved.
2.2.2.2. Asynchronous
This mode delegates the work done by the back end to a different thread. That way, throughput
and response time are (to a certain extend) decorrelated from the back end performance. The
drawback is that a small delay appears between the transaction commit and the index update and
a small overhead is introduced to deal with thread management.
2.3.1. Shared
With this strategy, Hibernate Search will share the same IndexReader, for a given Lucene index,
across multiple queries and threads provided that the IndexReader is still up-to-date. If the
IndexReader is not up-to-date, a new one is opened and provided. Each IndexReader is made
of several SegmentReaders. This strategy only reopens segments that have been modified or
created after last opening and shares the already loaded segments from the previous instance.
This strategy is the default.
16
Not-shared
2.3.2. Not-shared
Every time a query is executed, a Lucene IndexReader is opened. This strategy is not the most
efficient since opening and warming up an IndexReader can be a relatively expensive operation.
2.3.3. Custom
You can write your own reader strategy that suits your application needs by implementing
org.hibernate.search.reader.ReaderProvider. The implementation must be thread safe.
17
18
Chapter 3.
Configuration
3.1. Directory configuration
Apache Lucene has a notion of Directory to store the index files. The Directory implementation
can be customized, but Lucene comes bundled with a file system (FSDirectoryProvider) and
an in memory (RAMDirectoryProvider) implementation. DirectoryProviders are the Hibernate
Search abstraction around a Lucene Directory and handle the configuration and the initialization
of the underlying Lucene resources. Table 3.1, “List of built-in Directory Providers” shows the list
of the directory providers bundled with Hibernate Search.
org.hibernate.search.store.FSDirectoryProvider
File system based directory. indexBase : Base directory
The directory used will be
<indexBase>/< indexName > indexName: override
@Indexed.index (useful for
sharded indexes)
locking_strategy : optional,
see Section 3.10,
“LockFactory configuration”
org.hibernate.search.store.FSMasterDirectoryProvider
File system based directory. indexBase: Base directory
Like FSDirectoryProvider. It
also copies the index to a indexName: override
19
Chapter 3. Configuration
If the built-in directory providers do not fit your needs, you can write your own directory provider
by implementing the org.hibernate.store.DirectoryProvider interface.
20
Sharding indexes
Each indexed entity is associated to a Lucene index (an index can be shared by several entities
but this is not usually the case). You can configure the index through properties prefixed by
hibernate.search.indexname . Default properties inherited to all indexes can be defined using
the prefix hibernate.search.default.
hibernate.search.default.directory_provider
org.hibernate.search.store.FSDirectoryProvider
hibernate.search.default.indexBase=/usr/lucene/indexes
hibernate.search.Rules.directory_provider
org.hibernate.search.store.RAMDirectoryProvider
applied on
Example 3.2. Specifying the index name using the index parameter of @Indexed
@Indexed(index="Status")
public class Status { ... }
@Indexed(index="Rules")
public class Rule { ... }
will create a file system directory in /usr/lucene/indexes/Status where the Status entities will
be indexed, and use an in memory directory named Rules where Rule entities will be indexed.
You can easily define common rules like the directory provider and base directory, and override
those defaults later on on a per index basis.
Writing your own DirectoryProvider, you can utilize this configuration mechanism as well.
• A single index is so huge that index update times are slowing the application down.
21
Chapter 3. Configuration
• A typical search will only hit a sub-set of the index, such as when data is naturally segmented
by customer, region or application.
Hibernate Search allows you to index a given entity type into several sub indexes. Data is sharded
into the different sub indexes thanks to an IndexShardingStrategy. By default, no sharding
strategy is enabled, unless the number of shards is configured. To configure the number of shards
use the following property
hibernate.search.<indexName>.sharding_strategy.nbr_of_shards 5
The default sharding strategy, when shards are set up, splits the data according to the hash value
of the id string representation (generated by the Field Bridge). This ensures a fairly balanced
sharding. You can replace the strategy by implementing IndexShardingStrategy and by setting
the following property
hibernate.search.<indexName>.sharding_strategy
my.shardingstrategy.Implementation
It also allows for optimizing searches by selecting which shard to run the query onto.
By activating a filter (see Section 5.3.1, “Using filters in a sharded environment”),
a sharding strategy can select a subset of the shards used to answer a query
(IndexShardingStrategy.getDirectoryProvidersForQuery) and thus speed up the query
execution.
Each shard has an independent directory provider configuration as described in Section 3.1,
“Directory configuration”. The DirectoryProvider default name for the previous example are
<indexName>.0 to <indexName>.4. In other words, each shard has the name of it's owning index
followed by . (dot) and its index number.
hibernate.search.default.indexBase /usr/lucene/indexes
22
Sharing indexes (two entities into the same directory)
hibernate.search.Animal.sharding_strategy.nbr_of_shards 5
hibernate.search.Animal.directory_provider
org.hibernate.search.store.FSDirectoryProvider
hibernate.search.Animal.0.indexName Animal00
hibernate.search.Animal.3.indexBase /usr/lucene/sharded
hibernate.search.Animal.3.indexName Animal03
This configuration uses the default id string hashing strategy and shards the Animal index into 5
subindexes. All subindexes are FSDirectoryProvider instances and the directory where each
subindex is stored is as followed:
Note
This is only presented here so that you know the option is available. There is really
not much benefit in sharing indexes.
It is technically possible to store the information of more than one entity into a single Lucene index.
There are two ways to accomplish this:
• Configuring the underlying directory providers to point to the same physical index
directory. In practice, you set the property hibernate.search.[fully qualified entity
name].indexName to the same value. As an example let’s use the same index (directory) for the
Furniture and Animal entity. We just set indexName for both entities to for example “Animal”.
Both entities will then be stored in the Animal directory
hibernate.search.org.hibernate.search.test.shards.Furniture.indexName =
Animal
hibernate.search.org.hibernate.search.test.shards.Animal.indexName = Animal
• Setting the @Indexed annotation’s index attribute of the entities you want to merge to the same
value. If we again wanted all Furniture instances to be indexed in the Animal index along
23
Chapter 3. Configuration
You can define the worker configuration using the following properties
Property Description
hibernate.search.worker.backend Out of the box support for the Apache Lucene
back end and the JMS back end. Default
to lucene. Supports also jms, blackhole,
jgroupsMaster and jgroupsSlave.
24
JMS Master/Slave configuration
Every index update operation is sent to a JMS queue. Index querying operations are executed
on a local index copy.
25
Chapter 3. Configuration
## DirectoryProvider
# (remote) master location
hibernate.search.default.sourceBase = /mnt/mastervolume/lucenedirs/mastercopy
## Backend configuration
hibernate.search.worker.backend = jms
hibernate.search.worker.jms.connection_factory = /ConnectionFactory
hibernate.search.worker.jms.queue = queue/hibernatesearch
#optional jndi configuration (check your JMS provider for more information)
The refresh period should be higher that the expected time copy.
Every index update operation is taken from a JMS queue and executed. The master index is
copied on a regular basis.
## DirectoryProvider
# (remote) master location where information is copied to
hibernate.search.default.sourceBase = /mnt/mastervolume/lucenedirs/mastercopy
26
Master node
## Backend configuration
#Backend is the default lucene one
The refresh period should be higher that the expected time copy.
In addition to the Hibernate Search framework configuration, a Message Driven Bean should be
written and set up to process the index works queue through JMS.
@MessageDriven(activationConfig = {
@ActivationConfigProperty(propertyName="destinationType",
propertyValue="javax.jms.Queue"),
@ActivationConfigProperty(propertyName="destination", propertyValue="queue/
hibernatesearch"),
@ActivationConfigProperty(propertyName="DLQMaxResent", propertyValue="1")
} )
public class MDBSearchController extends AbstractJMSHibernateSearchController
implements MessageListener {
@PersistenceContext EntityManager em;
This example inherits from the abstract JMS controller class available in the Hibernate Search
source code and implements a JavaEE 5 MDB. This implementation is given as an example and,
while most likely be more complex, can be adjusted to make use of non Java EE Message Driven
Beans. For more information about the getSession() and cleanSessionIfNeeded(), please
check AbstractJMSHibernateSearchController's javadoc.
27
Chapter 3. Configuration
## configuration
28
JGroups channel configuration
<config xmlns="urn:org:jgroups"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="urn:org:jgroups file:schema/JGroups-2.8.xsd">
<UDP
mcast_addr="${jgroups.udp.mcast_addr:228.10.10.10}"
mcast_port="${jgroups.udp.mcast_port:45588}"
tos="8"
thread_naming_pattern="pl"
thread_pool.enabled="true"
thread_pool.min_threads="2"
thread_pool.max_threads="8"
thread_pool.keep_alive_time="5000"
thread_pool.queue_enabled="false"
thread_pool.queue_max_size="100"
thread_pool.rejection_policy="Run"/>
<PING timeout="1000" num_initial_members="3"/>
<MERGE2 max_interval="30000" min_interval="10000"/>
<FD_SOCK/>
<FD timeout="3000" max_tries="3"/>
<VERIFY_SUSPECT timeout="1500"/>
<pbcast.STREAMING_STATE_TRANSFER/>
<pbcast.FLUSH timeout="0"/>
</config>
UDP(mcast_addr=228.1.2.3;mcast_port=45566;ip_ttl=32):PING(timeout=3000;
num_initial_members=6):FD(timeout=5000):VERIFY_SUSPECT(timeout=1500):
pbcast.NAKACK(gc_lag=10;retransmit_timeout=3000):UNICAST(timeout=5000):
FRAG:pbcast.GMS(join_timeout=3000;shun=false;print_local_addr=true)
Master and slave nodes communicate over JGroups channel that is identified by this same name.
Name of the channel can be defined explicity, if not default HSearchCluster is used.
## Backend configuration
29
Chapter 3. Configuration
hibernate.search.worker.backend.jgroups.clusterName = Hibernate-Search-Cluster
• shared: share index readers across several queries. This strategy is the most efficient.
hibernate.search.reader.strategy = not-shared
hibernate.search.reader.strategy = my.corp.myapp.CustomReaderProvider
Hibernate Search is enabled out of the box when using Hibernate Annotations
or Hibernate EntityManager. If, for some reason you need to disable it, set
hibernate.search.autoregister_listeners to false. Note that there is no performance
penalty when the listeners are enabled but no entities are annotated as indexed.
To enable Hibernate Search in Hibernate Core (ie. if you don't use Hibernate Annotations), add
the FullTextIndexEventListener for the following six Hibernate events and also add it after the
default DefaultFlushEventListener, as in the following example.
<hibernate-configuration>
30
Automatic indexing
<session-factory>
...
<event type="post-update">
<listener
class="org.hibernate.search.event.FullTextIndexEventListener"/>
</event>
<event type="post-insert">
<listener
class="org.hibernate.search.event.FullTextIndexEventListener"/>
</event>
<event type="post-delete">
<listener
class="org.hibernate.search.event.FullTextIndexEventListener"/>
</event>
<event type="post-collection-recreate">
<listener
class="org.hibernate.search.event.FullTextIndexEventListener"/>
</event>
<event type="post-collection-remove">
<listener
class="org.hibernate.search.event.FullTextIndexEventListener"/>
</event>
<event type="post-collection-update">
<listener
class="org.hibernate.search.event.FullTextIndexEventListener"/>
</event>
<event type="flush">
<listener class="org.hibernate.event.def.DefaultFlushEventListener"/>
<listener
class="org.hibernate.search.event.FullTextIndexEventListener"/>
</event>
</session-factory>
</hibernate-configuration>
By default, every time an object is inserted, updated or deleted through Hibernate, Hibernate
Search updates the according Lucene index. It is sometimes desirable to disable that features
if either your index is read-only or if index updates are done in a batch way (see Section 6.3,
“Rebuilding the whole Index”).
hibernate.search.indexing_strategy manual
31
Chapter 3. Configuration
Note
In most case, the JMS backend provides the best of both world, a lightweight
event based system keeps track of all changes in the system, and the heavyweight
indexing process is done by a separate process or machine.
There are two sets of parameters allowing for different performance settings depending on the
use case. During indexing operations triggered by database modifications, the parameters are
grouped by the transaction keyword:
hibernate.search.[default|
<indexname>].indexwriter.transaction.<parameter_name>
When indexing occurs via FullTextSession.index() or via a MassIndexer (see Section 6.3,
“Rebuilding the whole Index”), the used properties are those grouped under the batch keyword:
hibernate.search.[default|<indexname>].indexwriter.batch.<parameter_name>
If no value is set for a .batch value in a specific shard configuration, Hibernate Search will look
at the index section, then at the default section:
hibernate.search.Animals.2.indexwriter.transaction.max_merge_docs 10
hibernate.search.Animals.2.indexwriter.transaction.merge_factor 20
hibernate.search.default.indexwriter.batch.max_merge_docs 100
This configuration will result in these settings applied to the second shard of Animals index:
• transaction.max_merge_docs = 10
• batch.max_merge_docs = 100
• transaction.merge_factor = 20
32
Tuning Lucene indexing performance
The default for all values is to leave them at Lucene's own default, so the listed values in the
following table actually depend on the version of Lucene you are using; values shown are relative
to version 2.4. For more information about Lucene indexing performances, please refer to the
Lucene documentation.
Warning
Previous versions had the batch parameters inherit from transaction properties.
This needs now to be explicitly set.
33
Chapter 3. Configuration
34
Tuning Lucene indexing performance
35
Chapter 3. Configuration
Tip
To tune the indexing speed it might be useful to time the object loading from database in isolation
from the writes to the index. To achieve this set the blackhole as worker backend and start you
indexing routines. This backend does not disable Hibernate Search: it will still generate the needed
changesets to the index, but will discard them instead of flushing them to the index. As opposite
to setting the hibernate.search.indexing_strategy to manual when using blackhole it will
possibly load more data to rebuild the index from associated entities.
hibernate.search.worker.backend blackhole
The recommended approach is to focus first on optimizing the object loading, and then use the
timings you achieve as a baseline to tune the indexing process.
The blackhole backend is not meant to be used in production, only as a tool to identify indexing
bottlenecks.
Some of these locking strategies require a filesystem level lock and may be used even on RAM
based indexes, but this is not recommended and of no practical use.
36
LockFactory configuration
native org.apache.lucene.store.NativeFSLockFactory
As does simple this also
marks the usage of the index
by creating a marker file, but
this one is using native OS
file locks so that even if your
application crashes the locks
will be cleaned up.
none org.apache.lucene.store.NoLockFactory
All changes to this index are
not coordinated by any lock;
test your application carefully
37
Chapter 3. Configuration
Configuration example:
hibernate.search.default.locking_strategy simple
hibernate.search.Animals.locking_strategy native
hibernate.search.Books.locking_strategy org.custom.components.MyLockingFactory
hibernate.search.error_handler log
The default exception handling occurs for both synchronous and asynchronous indexing.
Hibernate Search provides an easy mechanism to override the default error handling
implementation.
In order to provide your own implementation you must implement the ErrorHandler interface,
which provides handle ( ErrorContext context ) method. The ErrorContext provides a
reference to the primary LuceneWork that failed, the underlying exception and any subsequent
LuceneWork that could not be processed due to the primary exception.
38
Exception Handling Configuration
}
}
To register this error handler with Hibernate Search you must declare the CustomErrorHandler
fully qualified classname in the configuration properties:
hibernate.search.error_handler CustomerErrorHandler
39
40
Chapter 4.
@Entity
@Indexed(index="indexes/essays")
public class Essay {
...
}
The index attribute tells Hibernate what the Lucene directory name is (usually a directory
on your file system). It is recommended to define a base directory for all Lucene
indexes using the hibernate.search.default.indexBase property in your configuration
file. Alternatively you can specify a base directory per indexed entity by specifying
hibernate.search.<index>.indexBase, where <index> is the fully qualified classname of the
indexed entity. Each entity instance will be represented by a Lucene Document inside the given
index (aka Directory).
For each property (or attribute) of your entity, you have the ability to describe how it will be indexed.
The default (no annotation present) means that the property is ignored by the indexing process.
@Field does declare a property as indexed. When indexing an element to a Lucene document
you can specify how it is indexed:
• name : describe under which name, the property should be stored in the Lucene Document. The
default value is the property name (following the JavaBeans convention)
• store : describe whether or not the property is stored in the Lucene index. You can
store the value Store.YES (consuming more space in the index but allowing projection,
41
Chapter 4. Mapping entities t...
see Section 5.1.2.5, “Projection” for more information), store it in a compressed way
Store.COMPRESS (this does consume more CPU), or avoid any storage Store.NO (this is the
default value). When a property is stored, you can retrieve its original value from the Lucene
Document. This is not related to whether the element is indexed or not.
• index: describe how the element is indexed and the type of information store. The different
values are Index.NO (no indexing, ie cannot be found by a query), Index.TOKENIZED (use
an analyzer to process the property), Index.UN_TOKENIZED (no analyzer pre-processing),
Index.NO_NORMS (do not store the normalization data). The default value is TOKENIZED.
• termVector: describes collections of term-frequency pairs. This attribute enables term vectors
being stored during indexing so they are available within documents. The default value is
TermVector.NO.
Value Definition
TermVector.YES Store the term vectors of each document.
This produces two synchronized arrays,
one contains document terms and the other
contains the term's frequency.
TermVector.NO Do not store term vectors.
TermVector.WITH_OFFSETS Store the term vector and token offset
information. This is the same as
TermVector.YES plus it contains the starting
and ending offset position information for the
terms.
TermVector.WITH_POSITIONS Store the term vector and token position
information. This is the same as
TermVector.YES plus it contains the ordinal
positions of each occurrence of a term in a
document.
TermVector.WITH_POSITION_OFFSETS Store the term vector, token position and
offset information. This is a combination
of the YES, WITH_OFFSETS and
WITH_POSITIONS.
Whether or not you want to store the original data in the index depends on how you wish to use the
index query result. For a regular Hibernate Search usage storing is not necessary. However you
might want to store some fields to subsequently project them (see Section 5.1.2.5, “Projection”
for more information).
Whether or not you want to tokenize a property depends on whether you wish to search the
element as is, or by the words it contains. It make sense to tokenize a text field, but probably
not a date field.
42
Mapping properties multiple times
Note
Fields used for sorting must not be tokenized.
Finally, the id property of an entity is a special property used by Hibernate Search to ensure index
unicity of a given entity. By design, an id has to be stored and must not be tokenized. To mark
a property as index id, use the @DocumentId annotation. If you are using Hibernate Annotations
and you have specified @Id you can omit @DocumentId. The chosen entity id will also be used
as document id.
@Entity
@Indexed(index="indexes/essays")
public class Essay {
...
@Id
@DocumentId
public Long getId() { return id; }
@Lob
@Field(index=Index.TOKENIZED)
public String getText() { return text; }
}
Example 4.2, “Adding @DocumentId ad @Field annotations to an indexed entity” define an index
with three fields: id , Abstract and text . Note that by default the field name is decapitalized,
following the JavaBean specification
@Entity
@Indexed(index = "Book" )
43
Chapter 4. Mapping entities t...
...
}
In Example 4.3, “Using @Fields to map a property multiple times” the field summary is indexed
twice, once as summary in a tokenized way, and once as summary_forSort in an untokenized
way. @Field supports 2 attributes useful when @Fields is used:
• analyzer: defines a @Analyzer annotation per field rather than per property
• bridge: defines a @FieldBridge annotation per field rather than per property
See below for more information about analyzers and field bridges.
@Entity
@Indexed
public class Place {
@Id
@GeneratedValue
@DocumentId
private Long id;
44
Embedded and associated objects
@Entity
public class Address {
@Id
@GeneratedValue
private Long id;
@Field(index=Index.TOKENIZED)
private String street;
@Field(index=Index.TOKENIZED)
private String city;
@ContainedIn
@OneToMany(mappedBy="address")
private Set<Place> places;
...
}
In this example, the place fields will be indexed in the Place index. The Place index documents
will also contain the fields address.id, address.street, and address.city which you will be
able to query. This is enabled by the @IndexedEmbedded annotation.
Be careful. Because the data is denormalized in the Lucene index when using the
@IndexedEmbedded technique, Hibernate Search needs to be aware of any change in the Place
object and any change in the Address object to keep the index up to date. To make sure the Place
Lucene document is updated when it's Address changes, you need to mark the other side of the
bidirectional relationship with @ContainedIn.
@Entity
@Indexed
public class Place {
@Id
@GeneratedValue
@DocumentId
private Long id;
45
Chapter 4. Mapping entities t...
@Entity
public class Address {
@Id
@GeneratedValue
private Long id;
@Field(index=Index.TOKENIZED)
private String street;
@Field(index=Index.TOKENIZED)
private String city;
@ContainedIn
@OneToMany(mappedBy="address")
private Set<Place> places;
...
}
@Embeddable
public class Owner {
@Field(index = Index.TOKENIZED)
private String name;
...
}
Any @*ToMany, @*ToOne and @Embedded attribute can be annotated with @IndexedEmbedded.
The attributes of the associated class will then be added to the main entity index. In the previous
example, the index will contain the following fields
• id
• name
• address.street
• address.city
• address.ownedBy_name
46
Embedded and associated objects
The default prefix is propertyName., following the traditional object navigation convention. You
can override it using the prefix attribute as it is shown on the ownedBy property.
Note
The depth property is necessary when the object graph contains a cyclic dependency of classes
(not instances). For example, if Owner points to Place. Hibernate Search will stop including
Indexed embedded attributes after reaching the expected depth (or the object graph boundaries
are reached). A class having a self reference is an example of cyclic dependency. In our example,
because depth is set to 1, any @IndexedEmbedded attribute in Owner (if any) will be ignored.
Using @IndexedEmbedded for object associations allows you to express queries such as:
• Return places where name contains JBoss and where address city is Atlanta. In Lucene query
this would be
+name:jboss +address.city:atlanta
• Return places where name contains JBoss and where owner's name contain Joe. In Lucene
query this would be
+name:jboss +address.orderBy_name:joe
In a way it mimics the relational join operation in a more efficient way (at the cost of data
duplication). Remember that, out of the box, Lucene indexes have no notion of association, the
join operation is simply non-existent. It might help to keep the relational model normalized while
benefiting from the full text index speed and feature richness.
Note
An associated object can itself (but does not have to) be @Indexed
When @IndexedEmbedded points to an entity, the association has to be directional and the other
side has to be annotated @ContainedIn (as seen in the previous example). If not, Hibernate
Search has no way to update the root index when the associated entity is updated (in our example,
a Place index document has to be updated when the associated Address instance is updated).
Sometimes, the object type annotated by @IndexedEmbedded is not the object type targeted by
Hibernate and Hibernate Search. This is especially the case when interfaces are used in lieu
47
Chapter 4. Mapping entities t...
of their implementation. For this reason you can override the object type targeted by Hibernate
Search using the targetElement parameter.
@Entity
@Indexed
public class Address {
@Id
@GeneratedValue
@DocumentId
private Long id;
@Field(index= Index.TOKENIZED)
private String street;
...
}
@Embeddable
public class Owner implements Person { ... }
@Entity
@Indexed(index="indexes/essays")
@Boost(1.7f)
public class Essay {
...
@Id
@DocumentId
public Long getId() { return id; }
48
Dynamic boost factor
@Lob
@Field(index=Index.TOKENIZED, boost=@Boost(1.2f))
public String getText() { return text; }
@Field
public String getISBN() { return isbn; }
In our example, Essay's probability to reach the top of the search list will be multiplied by 1.7. The
summary field will be 3.0 (2 * 1.5 - @Field.boost and @Boost on a property are cumulative) more
important than the isbn field. The text field will be 1.2 times more important than the isbn field.
Note that this explanation in strictest terms is actually wrong, but it is simple and close enough to
reality for all practical purposes. Please check the Lucene documentation or the excellent Lucene
In Action from Otis Gospodnetic and Erik Hatcher.
@Entity
@Indexed
@DynamicBoost(impl = VIPBoostStrategy.class)
public class Person {
private PersonType type;
// ....
}
49
Chapter 4. Mapping entities t...
if ( person.getType().equals( PersonType.VIP ) ) {
return 2.0f;
}
else {
return 1.0f;
}
}
}
In Example 4.8, “Dynamic boost examle” a dynamic boost is defined on class level specifying
VIPBoostStrategy as implementation of the BoostStrategy interface to be used at indexing
time. You can place the @DynamicBoost either at class or field level. Depending on the placement
of the annotation either the whole entity is passed to the defineBoost method or just the annotated
field/property value. It's up to you to cast the passed object to the correct type. In the example all
indexed values of a VIP person would be double as important as the values of a normal person.
Note
Of course you can mix and match @Boost and @DynamicBoost annotations in your entity. All
defined boost factors are cummulative as described in Section 4.1.4, “Boost factor”.
4.1.6. Analyzer
The default analyzer class used to index tokenized fields is configurable through
the hibernate.search.analyzer property. The default value for this property is
org.apache.lucene.analysis.standard.StandardAnalyzer.
You can also define the analyzer class per entity, property and even per @Field (useful when
multiple fields are indexed from a single property).
@Entity
@Indexed
@Analyzer(impl = EntityAnalyzer.class)
public class MyEntity {
@Id
@GeneratedValue
@DocumentId
private Integer id;
@Field(index = Index.TOKENIZED)
50
Analyzer
@Field(index = Index.TOKENIZED)
@Analyzer(impl = PropertyAnalyzer.class)
private String summary;
...
}
In this example, EntityAnalyzer is used to index all tokenized properties (eg. name), except
summary and body which are indexed with PropertyAnalyzer and FieldAnalyzer respectively.
Caution
Mixing different analyzers in the same entity is most of the time a bad practice. It
makes query building more complex and results less predictable (for the novice),
especially if you are using a QueryParser (which uses the same analyzer for the
whole query). As a rule of thumb, for any given field the same analyzer should be
used for indexing and querying.
• a list of char filters: each char filter is responsible to pre-process input characters before the
tokenization. Char filters can add, change or remove characters; one common usage is for
characters normalization
• a tokenizer: responsible for tokenizing the input stream into individual words
• a list of filters: each filter is responsible to remove, modify or sometimes even add words into
the stream provided by the tokenizer
This separation of tasks - a list of char filters, and a tokenizer followed by a list of filters - allows
for easy reuse of each individual component and let you build your customized analyzer in a very
flexible way (just like Lego). Generally speaking the char filters do some pre-processing in the
character input, then the Tokenizer starts the tokenizing process by turning the character input
into tokens which are then further processed by the TokenFilters. Hibernate Search supports
51
Chapter 4. Mapping entities t...
this infrastructure by utilizing the Solr analyzer framework. Make sure to add solr-core.jar and
solr-solrj.jar to your classpath to use analyzer definitions. In case you also want to use the
snowball stemmer also include the lucene-snowball.jar. Other Solr analyzers might depend
on more libraries. For example, the PhoneticFilterFactory depends on commons-codec [http://
commons.apache.org/codec]. Your distribution of Hibernate Search provides these dependencies
in its lib directory.
@AnalyzerDef(name="customanalyzer",
charFilters = {
@CharFilterDef(factory = MappingCharFilterFactory.class, params = {
@Parameter(name = "mapping", value = "org/hibernate/search/
test/analyzer/solr/mapping-chars.properties")
})
},
tokenizer = @TokenizerDef(factory = StandardTokenizerFactory.class),
filters = {
@TokenFilterDef(factory = ISOLatin1AccentFilterFactory.class),
@TokenFilterDef(factory = LowerCaseFilterFactory.class),
@TokenFilterDef(factory = StopFilterFactory.class, params = {
@Parameter(name="words", value= "org/hibernate/search/
test/analyzer/solr/stoplist.properties" ),
@Parameter(name="ignoreCase", value="true")
})
})
public class Team {
...
}
A char filter is defined by its factory which is responsible for building the char filter and using
the optional list of parameters. In our example, a mapping char filter is used, and will replace
characters in the input based on the rules specified in the mapping file. A tokenizer is also defined
by its factory. This example use the standard tokenizer. A filter is defined by its factory which
is responsible for creating the filter instance using the optional parameters. In our example, the
StopFilter filter is built reading the dedicated words property file and is expected to ignore case.
The list of parameters is dependent on the tokenizer or filter factory.
Warning
Filters and char filters are applied in the order they are defined in the @AnalyzerDef
annotation. Make sure to think twice about this order.
Once defined, an analyzer definition can be reused by an @Analyzer declaration using the
definition name rather than declaring an implementation class.
52
Analyzer
@Entity
@Indexed
@AnalyzerDef(name="customanalyzer", ... )
public class Team {
@Id
@DocumentId
@GeneratedValue
private Integer id;
@Field
private String name;
@Field
private String location;
Analyzer instances declared by @AnalyzerDef are available by their name in the SearchFactory.
Analyzer analyzer =
fullTextSession.getSearchFactory().getAnalyzer("customanalyzer");
This is quite useful wen building queries. Fields in queries should be analyzed with the same
analyzer used to index the field so that they speak a common "language": the same tokens are
reused between the query and the indexing process. This rule has some exceptions but is true
most of the time. Respect it unless you know what you are doing.
53
Chapter 4. Mapping entities t...
54
Analyzer
So far all the introduced ways to specify an analyzer were static. However, there are use cases
where it is useful to select an analyzer depending on the current state of the entity to be indexed,
for example in multilingual applications. For an BlogEntry class for example the analyzer could
depend on the language property of the entry. Depending on this property the correct language
specific stemmer should be chosen to index the actual text.
To enable this
dynamic analyzer selection Hibernate Search introduces the
AnalyzerDiscriminator annotation. The following example demonstrates the usage of this
annotation:
@Entity
@Indexed
@AnalyzerDefs({
@AnalyzerDef(name = "en",
tokenizer = @TokenizerDef(factory = StandardTokenizerFactory.class),
filters = {
@TokenFilterDef(factory = LowerCaseFilterFactory.class),
@TokenFilterDef(factory = EnglishPorterFilterFactory.class
)
}),
@AnalyzerDef(name = "de",
tokenizer = @TokenizerDef(factory = StandardTokenizerFactory.class),
filters = {
@TokenFilterDef(factory = LowerCaseFilterFactory.class),
@TokenFilterDef(factory = GermanStemFilterFactory.class)
})
})
public class BlogEntry {
@Id
@GeneratedValue
@DocumentId
private Integer id;
@Field
@AnalyzerDiscriminator(impl = LanguageDiscriminator.class)
private String language;
55
Chapter 4. Mapping entities t...
@Field
private String text;
// standard getter/setter
...
}
The prerequisite for using @AnalyzerDiscriminator is that all analyzers which are going to
be used are predefined via @AnalyzerDef definitions. If this is the case one can place the
@AnalyzerDiscriminator annotation either on the class or on a specific property of the entity for
which to dynamically select an analyzer. Via the impl parameter of the AnalyzerDiscriminator
you specify a concrete implementation of the Discriminator interface. It is up to you to
provide an implementation for this interface. The only method you have to implement is
getAnalyzerDefinitionName() which gets called for each field added to the Lucene document.
The entity which is getting indexed is also passed to the interface method. The value parameter
is only set if the AnalyzerDiscriminator is placed on property level instead of class level. In this
case the value represents the current value of this property.
An implemention of the Discriminator interface has to return the name of an existing analyzer
definition if the analyzer should be set dynamically or null if the default analyzer should not be
overridden. The given example assumes that the language parameter is either 'de' or 'en' which
matches the specified names in the @AnalyzerDefs.
Note
56
Analyzer
During indexing time, Hibernate Search is using analyzers under the hood for you. In some
situations, retrieving analyzers can be handy. If your domain model makes use of multiple
analyzers (maybe to benefit from stemming, use phonetic approximation and so on), you need to
make sure to use the same analyzers when you build your query.
Note
This rule can be broken but you need a good reason for it. If you are unsure, use
the same analyzers.
You can retrieve the scoped analyzer for a given entity used at indexing time by Hibernate Search.
A scoped analyzer is an analyzer which applies the right analyzers depending on the field indexed:
multiple analyzers can be defined on a given entity each one working on an individual field, a
scoped analyzer unify all these analyzers into a context-aware analyzer. While the theory seems
a bit complex, using the right analyzer in a query is very easy.
Example 4.13. Using the scoped analyzer when building a full-text query
org.apache.lucene.search.Query luceneQuery =
parser.parse( "title:sky Or title_stemmed:diamond" );
org.hibernate.Query fullTextQuery =
fullTextSession.createFullTextQuery( luceneQuery, Song.class );
In the example above, the song title is indexed in two fields: the standard analyzer is used in the
field title and a stemming analyzer is used in the field title_stemmed. By using the analyzer
provided by the search factory, the query uses the appropriate analyzer depending on the field
targeted.
If your query targets more that one query and you wish to use your standard analyzer, make sure
to describe it using an analyzer definition. You can retrieve analyzers by their definition name
using searchFactory.getAnalyzer(String).
57
Chapter 4. Mapping entities t...
null
null elements are not indexed. Lucene does not support null elements and this does not make
much sense either.
java.lang.String
String are indexed as is
short, Short, integer, Integer, long, Long, float, Float, double, Double, BigInteger, BigDecimal
Numbers are converted in their String representation. Note that numbers cannot be compared
by Lucene (ie used in ranged queries) out of the box: they have to be padded
Note
java.util.Date
Dates are stored as yyyyMMddHHmmssSSS in GMT time (200611072203012 for Nov 7th of
2006 4:03PM and 12ms EST). You shouldn't really bother with the internal format. What is
important is that when using a DateRange Query, you should know that the dates have to
be expressed in GMT time.
@Entity
@Indexed
public class Meeting {
@Field(index=Index.UN_TOKENIZED)
58
Custom Bridge
@DateBridge(resolution=Resolution.MINUTE)
private Date date;
...
Warning
java.net.URI, java.net.URL
URI and URL are converted to their string representation
java.lang.Class
Class are converted to their fully qualified class name. The thread context classloader is used
when the class is rehydrated
4.2.2.1. StringBridge
/**
* Padding Integer bridge.
* All numbers will be padded with 0 to match 5 digits
*
* @author Emmanuel Bernard
*/
public class PaddedIntegerBridge implements StringBridge {
59
Chapter 4. Mapping entities t...
Then any property or field can use this bridge thanks to the @FieldBridge annotation
@FieldBridge(impl = PaddedIntegerBridge.class)
private Integer length;
Parameters can be passed to the Bridge implementation making it more flexible. The Bridge
implementation implements a ParameterizedBridge interface, and the parameters are passed
through the @FieldBridge annotation.
//property
@FieldBridge(impl = PaddedIntegerBridge.class,
60
Custom Bridge
All implementations have to be thread-safe, but the parameters are set during initialization and
no special care is required at this stage.
If you expect to use your bridge implementation on an id property (ie annotated with @DocumentId
), you need to use a slightly extended version of StringBridge named TwoWayStringBridge.
Hibernate Search needs to read the string representation of the identifier and generate the object
out of it. There is no difference in the way the @FieldBridge annotation is used.
61
Chapter 4. Mapping entities t...
//id property
@DocumentId
@FieldBridge(impl = PaddedIntegerBridge.class,
params = @Parameter(name="padding", value="10")
private Integer id;
4.2.2.2. FieldBridge
Some use cases require more than a simple object to string translation when mapping a property
to a Lucene index. To give you the greatest possible flexibility you can also implement a bridge
as a FieldBridge. This interface gives you a property value and let you map it the way you want
in your Lucene Document. The interface is very similar in its concept to the Hibernate UserTypes.
You can for example store a given property in two different document fields:
/**
* Store the date in 3 different fields - year, month, day - to ease Range Query per
* year, month or day (eg get all the elements of December for the last 5 years).
* @author Emmanuel Bernard
*/
public class DateSplitBridge implements FieldBridge {
private final static TimeZone GMT = TimeZone.getTimeZone("GMT");
// set year
luceneOptions.addFieldToDocument(
name + ".year",
String.valueOf( year ),
document );
62
Custom Bridge
name + ".month",
month < 10 ? "0" : "" + String.valueOf( month ),
document );
//property
@FieldBridge(impl = DateSplitBridge.class)
private Date date;
In the previous example the fields where not added directly to Document but we where delegating
this task to the LuceneOptions helper; this will apply the options you have selected on @Field,
like Store or TermVector options, or apply the choosen @Boost value. It is especially useful to
encapsulate the complexity of COMPRESS implementations so it's recommended to delegate to
LuceneOptions to add fields to the Document, but nothing stops you from editing the Document
directly and ignore the LuceneOptions in case you need to.
Tip
Classes like LuceneOptions are created to shield your application from changes
in Lucene API and simplify your code. Use them if you can, but if you need more
flexibility you're not required to.
4.2.2.3. ClassBridge
It is sometimes useful to combine more than one property of a given entity and index this
combination in a specific way into the Lucene index. The @ClassBridge and @ClassBridge
annotations can be defined at the class level (as opposed to the property level). In this case the
custom field bridge implementation receives the entity instance as the value parameter instead of
a particular property. Though not shown in this example, @ClassBridge supports the termVector
attribute discussed in section Section 4.1.1, “Basic mapping”.
@Entity
@Indexed
@ClassBridge(name="branchnetwork",
index=Index.TOKENIZED,
store=Store.YES,
63
Chapter 4. Mapping entities t...
impl = CatFieldsClassBridge.class,
params = @Parameter( name="sepChar", value=" " ) )
public class Department {
private int id;
private String network;
private String branchHead;
private String branch;
private Integer maxEmployees
...
}
In this example, the particular CatFieldsClassBridge is applied to the department instance, the
field bridge then concatenate both branch and network and index the concatenation.
64
Providing your own id
Warning
This part of the documentation is a work in progress.
You can provide your own id for Hibernate Search if you are extending the internals. You will have
to generate a unique value so it can be given to Lucene to be indexed. This will have to be given
to Hibernate Search when you create an org.hibernate.search.Work object - the document id is
required in the constructor.
Warning
This feature is considered experimental. While stable code-wise, the API is subject
to change in the future.
Although the recommended approach for mapping indexed entities is to use annotations, it is
sometimes more convenient to use a different approach:
• the same entity is mapped differently depending on deployment needs (customization for
clients)
65
Chapter 4. Mapping entities t...
• some automatization process requires the dynamic mapping of many entities sharing a common
traits
While it has been a popular demand in the past, the Hibernate team never found the idea of an
XML alternative to annotations appealing due to it's heavy duplication, lack of code refactoring
safety, because it did not cover all the use case spectrum and because we are in the 21st century :)
Th idea of a programmatic API was much more appealing and has now become a reality. You can
programmatically and safely define your mapping using a programmatic API: you define entities
and fields as indexable by using mapping classes which effectively mirror the annotation concepts
in Hibernate Search. Note that fan(s) of XML approach can design their own schema and use the
programmatic API to create the mapping while parsing the XML stream.
In order to use the programmatic model you must first construct a SearchMapping object.
This object is passed to Hibernate Search via a property set to the Configuration
object. The property key is hibernate.search.model_mapping or it's type-safe representation
Environment.MODEL_MAPPING.
//or in JPA
SearchMapping mapping = new SearchMapping();
[...]
Map<String,String> properties = new HashMap<String,String)(1);
properties.put( Environment.MODEL_MAPPING, mapping );
EntityManagerFactory emf = Persistence.createEntityManagerFactory( "userPU",
properties );
The SearchMapping is the root object which contains all the necessary indexable entities and
fields. From there, the SearchMapping object exposes a fluent (and thus intuitive) API to express
your mappings: it contextually exposes the relevant mapping options in a type-safe way, just let
your IDE autocompletion feature guide you through.
Today, the programmatic API cannot be used on a class annotated with Hibernate Search
annotations, chose one approach or the other. Also note that the same default values apply in
annotations and the programmatic API. For example, the @Field.name is defaulted to the property
name and does not have to be set.
Each core concept of the programmatic API has a corresponding example to depict how the
same definition would look using annotation. Therefore seeing an annotation example of the
programmatic approach should give you a clear picture of what Hibernate Search will build with
the marked entities and associated properties.
66
Mapping an entity as indexable
mapping.entity(Address.class)
.indexed()
.indexName("Address_Index"); //optional
As you can see you must first create a SearchMapping object which is the root object that is then
passed to the Configuration object as property. You must declare an entity and if you wish to
make that entity as indexable then you must call the indexed() method. The indexed() method
has an optional indexName(String indexName) which can be used to change the default index
name that is created by Hibernate Search. Using the annotation model the above can be achieved
as:
@Entity
@Indexed(index="Address_Index")
public class Address {
....
}
mapping.entity(Address.class).indexed()
.property("addressId", ElementType.FIELD) //field access
.documentId()
.name("id");
67
Chapter 4. Mapping entities t...
The above is equivalent to annotating a property in the entity as @DocumentId as seen in the
following example:
@Entity
@Indexed
public class Address {
@Id
@GeneratedValue
@DocumentId(name="id")
private Long addressId;
....
}
mapping
.analyzerDef( "ngram", StandardTokenizerFactory.class )
.filter( LowerCaseFilterFactory.class )
.filter( NGramFilterFactory.class )
.param( "minGramSize", "3" )
.param( "maxGramSize", "3" )
.analyzerDef( "en", StandardTokenizerFactory.class )
.filter( LowerCaseFilterFactory.class )
.filter( EnglishPorterFilterFactory.class )
.analyzerDef( "de", StandardTokenizerFactory.class )
.filter( LowerCaseFilterFactory.class )
.filter( GermanStemFilterFactory.class )
.entity(Address.class).indexed()
.property("addressId", ElementType.METHOD) //getter access
68
Defining full text filter definitions
.documentId()
.name("id");
The analyzer mapping defined above is equivalent to the annotation model using @AnalyzerDef
in conjunction with @AnalyzerDefs:
@Indexed
@Entity
@AnalyzerDefs({
@AnalyzerDef(name = "ngram",
tokenizer = @TokenizerDef(factory = StandardTokenizerFactory.class),
filters = {
@TokenFilterDef(factory = LowerCaseFilterFactory.class),
@TokenFilterDef(factory = NGramFilterFactory.class,
params = {
@Parameter(name = "minGramSize",value = "3"),
@Parameter(name = "maxGramSize",value = "3")
})
}),
@AnalyzerDef(name = "en",
tokenizer = @TokenizerDef(factory = StandardTokenizerFactory.class),
filters = {
@TokenFilterDef(factory = LowerCaseFilterFactory.class),
@TokenFilterDef(factory = EnglishPorterFilterFactory.class)
}),
@AnalyzerDef(name = "de",
tokenizer = @TokenizerDef(factory = StandardTokenizerFactory.class),
filters = {
@TokenFilterDef(factory = LowerCaseFilterFactory.class),
@TokenFilterDef(factory = GermanStemFilterFactory.class)
})
})
public class Address {
...
}
The programmatic API provides easy mechanism for defining full text filter definitions which
is available via @FullTextFilterDef and @FullTextFilterDefs. Note that contrary to the
69
Chapter 4. Mapping entities t...
annotation equivalent, full text filter definitions are a global construct and are not tied to an entity.
The next example depicts the creation of full text filter definition using the fullTextFilterDef
method.
mapping
.analyzerDef( "en", StandardTokenizerFactory.class )
.filter( LowerCaseFilterFactory.class )
.filter( EnglishPorterFilterFactory.class )
.fullTextFilterDef("security", SecurityFilterFactory.class)
.cache(FilterCacheModeType.INSTANCE_ONLY)
.entity(Address.class)
.indexed()
.property("addressId", ElementType.METHOD)
.documentId()
.name("id")
.property("street1", ElementType.METHOD)
.field()
.analyzer("en")
.store(Store.YES)
.field()
.name("address_data")
.analyzer("en")
.store(Store.NO);
The previous example can effectively been seen as annotating your entity with
@FullTextFilterDef like below:
@Entity
@Indexed
@AnalyzerDefs({
@AnalyzerDef(name = "en",
tokenizer = @TokenizerDef(factory = StandardTokenizerFactory.class),
filters = {
@TokenFilterDef(factory = LowerCaseFilterFactory.class),
@TokenFilterDef(factory = EnglishPorterFilterFactory.class)
})
})
@FullTextFilterDefs({
70
Defining fields for indexing
@Id
@GeneratedValue
@DocumentId(name="id")
pubblic Long getAddressId() {...};
@Fields({
@Field(index=Index.TOKENIZED, store=Store.YES,
analyzer=@Analyzer(definition="en")),
@Field(name="address_data", analyzer=@Analyzer(definition="en"))
})
public String getAddress1() {...};
......
When defining fields for indexing using the programmatic API, call field() on the
property(String propertyName, ElementType elementType) method. From field() you
can specify the name, index, store, bridge and analyzer definitions.
mapping
.analyzerDef( "en", StandardTokenizerFactory.class )
.filter( LowerCaseFilterFactory.class )
.filter( EnglishPorterFilterFactory.class )
.entity(Address.class).indexed()
.property("addressId", ElementType.METHOD)
.documentId()
.name("id")
.property("street1", ElementType.METHOD)
.field()
.analyzer("en")
.store(Store.YES)
.index(Index.TOKENIZED) //no useful here as it's the default
.field()
.name("address_data")
.analyzer("en");
71
Chapter 4. Mapping entities t...
The above example of marking fields as indexable is equivalent to defining fields using @Field
as seen below:
@Entity
@Indexed
@AnalyzerDefs({
@AnalyzerDef(name = "en",
tokenizer = @TokenizerDef(factory = StandardTokenizerFactory.class),
filters = {
@TokenFilterDef(factory = LowerCaseFilterFactory.class),
@TokenFilterDef(factory = EnglishPorterFilterFactory.class)
})
})
public class Address {
@Id
@GeneratedValue
@DocumentId(name="id")
private Long getAddressId() {...};
@Fields({
@Field(index=Index.TOKENIZED, store=Store.YES,
analyzer=@Analyzer(definition="en")),
@Field(name="address_data", analyzer=@Analyzer(definition="en"))
})
public String getAddress1() {...}
......
}
In this section you will see how to programmatically define entities to be embedded into the
indexed entity similar to using the @IndexEmbedded model. In order to define this you must mark
the property as indexEmbedded. The is the option to add a prefix to the embedded entity definition
and this can be done by calling prefix as seen in the example below:
72
Programmatically defining embedded entities
mappping
.entity(ProductCatalog.class)
.indexed()
.property("catalogId", ElementType.METHOD)
.documentId()
.name("id")
.property("title", ElementType.METHOD)
.field()
.index(Index.TOKENIZED)
.store(Store.NO)
.property("description", ElementType.METHOD)
.field()
.index(Index.TOKENIZED)
.store(Store.NO)
.property("items", ElementType.METHOD)
.indexEmbedded()
.prefix("catalog.items"); //optional
The next example shows the same definition using annotation (@IndexEmbedded):
@Entity
@Indexed
public class ProductCatalog {
@Id
@GeneratedValue
@DocumentId(name="id")
public Long getCatalogId() {...}
@Field(store=Store.NO, index=Index.TOKENIZED)
public String getTitle() {...}
@Field(store=Store.NO, index=Index.TOKENIZED)
public String getDescription();
@OneToMany(fetch = FetchType.LAZY)
@IndexColumn(name = "list_position")
@Cascade(org.hibernate.annotations.CascadeType.ALL)
@IndexEmbedded(prefix="catalog.items")
73
Chapter 4. Mapping entities t...
...
mappping
.entity(ProductCatalog.class)
.indexed()
.property("catalogId", ElementType.METHOD)
.documentId()
.property("title", ElementType.METHOD)
.field()
.property("description", ElementType.METHOD)
.field()
.property("items", ElementType.METHOD)
.indexEmbedded()
.entity(Item.class)
.property("description", ElementType.METHOD)
.field()
.property("productCatalog", ElementType.METHOD)
.containedIn();
@Entity
@Indexed
public class ProductCatalog {
@Id
@GeneratedValue
@DocumentId
74
Date/Calendar Bridge
@Field
public String getTitle() {...}
@Field
public String getDescription() {...}
@OneToMany(fetch = FetchType.LAZY)
@IndexColumn(name = "list_position")
@Cascade(org.hibernate.annotations.CascadeType.ALL)
@IndexEmbedded
private List<Item> getItems() {...}
...
@Entity
public class Item {
@Id
@GeneratedValue
private Long itemId;
@Field
public String getDescription() {...}
...
}
mapping
75
Chapter 4. Mapping entities t...
.entity(Address.class)
.indexed()
.property("addressId", ElementType.FIELD)
.documentId()
.property("street1", ElementType.FIELD()
.field()
.property("createdOn", ElementType.FIELD)
.field()
.dateBridge(Resolution.DAY)
.property("lastUpdated", ElementType.FIELD)
.calendarBridge(Resolution.DAY);
See below for defining the above using @CalendarBridge and @DateBridge:
@Entity
@Indexed
public class Address {
@Id
@GeneratedValue
@DocumentId
private Long addressId;
@Field
private String address1;
@Field
@DateBridge(resolution=Resolution.DAY)
private Date createdOn;
@CalendarBridge(resolution=Resolution.DAY)
private Calendar lastUpdated;
...
}
76
Defining bridges
parameters required for the bridge class. The below shows an example of programmatically
defining a bridge:
mapping
.entity(Address.class)
.indexed()
.property("addressId", ElementType.FIELD)
.documentId()
.property("street1", ElementType.FIELD)
.field()
.field()
.name("street1_abridged")
.bridge( ConcatStringBridge.class )
.param( "size", "4" );
The above can equally be defined using annotations, as seen in the next example.
@Entity
@Indexed
@Id
@GeneratedValue
@DocumentId(name="id")
private Long addressId;
@Fields({
@Field,
@Field(name="street1_abridged",
bridge = @FieldBridge( impl = ConcatStringBridge.class,
params = @Parameter( name="size", value="4" ))
})
private String address1;
...
}
77
Chapter 4. Mapping entities t...
You can define class bridges on entities programmatically. This is shown in the next example:
mapping
.entity(Departments.class)
.classBridge(CatDeptsFieldsClassBridge.class)
.name("branchnetwork")
.index(Index.TOKENIZED)
.store(Store.YES)
.param("sepChar", " ")
.classBridge(EquipmentType.class)
.name("equiptype")
.index(Index.TOKENIZED)
.store(Store.YES)
.param("C", "Cisco")
.param("D", "D-Link")
.param("K", "Kingston")
.param("3", "3Com")
.indexed();
@Entity
@Indexed
@ClassBridges ( {
@ClassBridge(name="branchnetwork",
index= Index.TOKENIZED,
store= Store.YES,
impl = CatDeptsFieldsClassBridge.class,
params = @Parameter( name="sepChar", value=" " ) ),
@ClassBridge(name="equiptype",
index= Index.TOKENIZED,
store= Store.YES,
impl = EquipmentType.class,
params = {@Parameter( name="C", value="Cisco" ),
@Parameter( name="D", value="D-Link" ),
78
Mapping dynamic boost
....
You can apply a dynamic boost factor on either a field or a whole entity:
mapping
.entity(DynamicBoostedDescLibrary.class)
.indexed()
.dynamicBoost(CustomBoostStrategy.class)
.property("libraryId", ElementType.FIELD)
.documentId().name("id")
.property("name", ElementType.FIELD)
.dynamicBoost(CustomFieldBoostStrategy.class);
.field()
.store(Store.YES)
The next example shows the equivalent mapping using the @DynamicBoost annotation:
@Entity
@Indexed
@DynamicBoost(impl = CustomBoostStrategy.class)
public class DynamicBoostedDescriptionLibrary {
@Id
@GeneratedValue
@DocumentId
private int id;
79
Chapter 4. Mapping entities t...
@Field(store = Store.YES)
@DynamicBoost(impl = CustomFieldBoostStrategy.class)
private String name;
public DynamicBoostedDescriptionLibrary() {
dynScore = 1.0f;
}
.......
80
Chapter 5.
Querying
The second most important capability of Hibernate Search is the ability to execute a Lucene query
and retrieve entities managed by an Hibernate session, providing the power of Lucene without
leaving the Hibernate paradigm, and giving another dimension to the Hibernate classic search
mechanisms (HQL, Criteria query, native SQL query). Preparing and executing a query consists
of four simple steps:
• Creating a FullTextSession
To access the querying facilities, you have to use an FullTextSession. This Search specific
session wraps a regular org.hibernate.Session to provide query and indexing capabilities.
The actual search facility is built on native Lucene queries which the following example illustrates.
org.apache.lucene.queryParser.QueryParser parser =
new QueryParser("title", new StopAnalyzer() );
The Hibernate query built on top of the Lucene query is a regular org.hibernate.Query, which
means you are in the same paradigm as the other Hibernate query facilities (HQL, Native or
Criteria). The regular list() , uniqueResult(), iterate() and scroll() methods can be used.
In case you are using the Java Persistence APIs of Hibernate (aka EJB 3.0 Persistence), the
same extensions exist:
81
Chapter 5. Querying
EntityManager em = entityManagerFactory.createEntityManager();
FullTextEntityManager fullTextEntityManager =
org.hibernate.search.jpa.Search.getFullTextEntityManager(em);
...
org.apache.lucene.queryParser.QueryParser parser =
new QueryParser("title", new StopAnalyzer() );
The following examples we will use the Hibernate APIs but the same example can be easily
rewritten with the Java Persistence API by just adjusting the way the FullTextQuery is retrieved.
5.1.2.1. Generality
Once the Lucene query is built, it needs to be wrapped into an Hibernate Query.
82
Building a Hibernate Search query
If not specified otherwise, the query will be executed against all indexed entities, potentially
returning all types of indexed classes. It is advised, from a performance point of view, to restrict
the returned types:
org.hibernate.Query fullTextQuery =
fullTextSession.createFullTextQuery( luceneQuery, Customer.class );
// or
fullTextQuery = fullTextSession.createFullTextQuery( luceneQuery, Item.class,
Actor.class );
The first example returns only matching Customers, the second returns matching Actors and
Items. The type restriction is fully polymorphic which means that if there are two indexed
subclasses Salesman and Customer of the baseclass Person, it is possible to just specify
Person.class in order to filter on result types.
5.1.2.2. Pagination
Out of performance reasons it is recommended to restrict the number of returned objects per
query. In fact is a very common use case anyway that the user navigates from one page to an
other. The way to define pagination is exactly the way you would define pagination in a plain HQL
or Criteria query.
org.hibernate.Query fullTextQuery =
fullTextSession.createFullTextQuery( luceneQuery, Customer.class );
fullTextQuery.setFirstResult(15); //start from the 15th element
fullTextQuery.setMaxResults(10); //return 10 elements
Note
It is still possible to get the total number of matching elements regardless of the
pagination via fulltextQuery.getResultSize()
5.1.2.3. Sorting
Apache Lucene provides a very flexible and powerful way to sort results. While the default sorting
(by relevance) is appropriate most of the time, it can be interesting to sort by one or several other
properties. In order to do so set the Lucene Sort object to apply a Lucene sorting strategy.
83
Chapter 5. Querying
One can notice the FullTextQuery interface which is a sub interface of org.hibernate.Query.
Be aware that fields used for sorting must not be tokenized.
It is often useful, however, to refine the fetching strategy for a specific use case.
In this example, the query will return all Books matching the luceneQuery. The authors collection
will be loaded from the same query using an SQL outer join.
When defining a criteria query, it is not needed to restrict the entity types returned while creating
the Hibernate Search query from the full text session: the type is guessed from the criteria query
itself. Only fetch mode can be adjusted, refrain from applying any other restriction.
One cannot use setCriteriaQuery if more than one entity type is expected to be returned.
5.1.2.5. Projection
For some use cases, returning the domain object (graph) is overkill. Only a small subset of the
properties is necessary. Hibernate Search allows you to return a subset of properties:
Example 5.9. Using projection instead of returning the full domain object
84
Building a Hibernate Search query
Integer id = firstResult[0];
String summary = firstResult[1];
String body = firstResult[2];
String authorName = firstResult[3];
Hibernate Search extracts the properties from the Lucene index and convert them back to their
object representation, returning a list of Object[]. Projections avoid a potential database round
trip (useful if the query response time is critical), but has some constraints:
• you can only project simple properties of the indexed entity or its embedded associations. This
means you cannot project a whole embedded entity.
• projection does not work on collections or maps which are indexed via @IndexedEmbedded
Projection is useful for another kind of use cases. Lucene provides some metadata information
to the user about the results. By using some special placeholders, the projection mechanism can
retrieve them:
You can mix and match regular fields and special placeholders. Here is the list of available
placeholders:
• FullTextQuery.THIS: returns the initialized and managed entity (as a non projected query would
have done).
85
Chapter 5. Querying
• FullTextQuery.SCORE: returns the document score in the query. Scores are handy to compare
one result against an other for a given query but are useless when comparing the result of
different queries.
• FullTextQuery.EXPLANATION: returns the Lucene Explanation object for the matching object/
document in the given query. Do not use if you retrieve a lot of data. Running explanation
typically is as costly as running the whole Lucene query per matching element. Make sure you
use projection!
If you wish to minimize Lucene document loading, scroll() is more appropriate. Don't forget to
close the ScrollableResults object when you're done, since it keeps Lucene resources. If you
expect to use scroll, but wish to load objects in batch, you can use query.setFetchSize().
When an object is accessed, and if not already loaded, Hibernate Search will load the next
fetchSize objects in one pass.
• to implement a multi step search engine (adding approximation if the restricted query return no
or not enough results)
Of course it would be too costly to retrieve all the matching documents. Hibernate Search allows
you to retrieve the total number of matching documents regardless of the pagination parameters.
86
ResultTransformer
Even more interesting, you can retrieve the number of matching elements without triggering a
single object load.
Note
Like Google, the number of results is approximative if the index is not fully up-to-
date with the database (asynchronous cluster for example).
5.2.3. ResultTransformer
Especially when using projection, the data structure returned by a query (an object array in this
case), is not always matching the application needs. It is possible to apply a ResultTransformer
operation post query to match the targeted data structure:
query.setResultTransformer(
new StaticAliasToBeanResultTransformer( BookView.class, "title", "author" )
);
List<BookView> results = (List<BookView>) query.list();
for(BookView view : results) {
log.info( "Book: " + view.getTitle() + ", " + view.getAuthor() );
}
87
Chapter 5. Querying
• Use projection
The first approach takes a document id as a parameter and return the Explanation object. The
document id can be retrieved using projection and the FullTextQuery.DOCUMENT_ID constant.
Warning
The Document id has nothing to do with the entity id. Do not mess up these two
notions.
Be careful, building the explanation object is quite expensive, it is roughly as expensive as running
the Lucene query again. Don't do it if you don't need the object
5.3. Filters
Apache Lucene has a powerful feature that allows to filter query results according to a custom
filtering process. This is a very powerful way to apply additional data restrictions, especially since
filters can be cached and reused. Some interesting use cases are:
• security
88
Filters
Hibernate Search pushes the concept further by introducing the notion of parameterizable named
filters which are transparently cached. For people familiar with the notion of Hibernate Core filters,
the API is very similar:
In this example we enabled two filters on top of the query. You can enable (or disable) as many
filters as you like.
Declaring filters is done through the @FullTextFilterDef annotation. This annotation can be on
any @Indexed entity regardless of the query the filter is later applied to. This implies that filter
definitions are global and their names must be unique. A SearchException is thrown in case two
different @FullTextFilterDef annotations with the same name are defined. Each named filter
has to specify its actual filter implementation.
@Entity
@Indexed
@FullTextFilterDefs( {
@FullTextFilterDef(name = "bestDriver", impl = BestDriversFilter.class),
@FullTextFilterDef(name = "security", impl = SecurityFilterFactory.class)
})
public class Driver { ... }
89
Chapter 5. Querying
If your Filter creation requires additional steps or if the filter you want to use does not have a no-
arg constructor, you can use the factory pattern:
@Entity
@Indexed
@FullTextFilterDef(name = "bestDriver", impl = BestDriversFilterFactory.class)
public class Driver { ... }
@Factory
public Filter getFilter() {
//some additional steps to cache the filter results per IndexReader
Filter bestDriversFilter = new BestDriversFilter();
return new CachingWrapperFilter(bestDriversFilter);
}
}
Hibernate Search will look for a @Factory annotated method and use it to build the filter instance.
The factory must have a no-arg constructor. For people familiar with JBoss Seam, this is similar
to the component factory pattern, but the annotation is different!
Named filters come in handy where parameters have to be passed to the filter. For example a
security filter might want to know which security level you want to apply:
Each parameter name should have an associated setter on either the filter or filter factory of the
targeted named filter definition.
90
Filters
/**
* injected parameter
*/
public void setLevel(Integer level) {
this.level = level;
}
@Key
public FilterKey getKey() {
StandardFilterKey key = new StandardFilterKey();
key.addParameter( level );
return key;
}
@Factory
public Filter getFilter() {
Query query = new TermQuery( new Term("level", level.toString() ) );
return new CachingWrapperFilter( new QueryWrapperFilter(query) );
}
}
Note the method annotated @Key returning a FilterKey object. The returned object has a special
contract: the key object must implement equals() / hashCode() so that 2 keys are equal if and
only if the given Filter types are the same and the set of parameters are the same. In other
words, 2 filter keys are equal if and only if the filters from which the keys are generated can be
interchanged. The key object is used as a key in the cache mechanism.
In most cases, using the StandardFilterKey implementation will be good enough. It delegates
the equals() / hashCode() implementation to each of the parameters equals and hashcode
methods.
As mentioned before the defined filters are per default cached and the cache uses a combination
of hard and soft references to allow disposal of memory when needed. The hard reference
cache keeps track of the most recently used filters and transforms the ones least used to
SoftReferences when needed. Once the limit of the hard reference cache is reached additional
filters are cached as SoftReferences. To adjust the size of the hard reference cache, use
hibernate.search.filter.cache_strategy.size (defaults to 128). For advanced use of filter
caching, you can implement your own FilterCachingStrategy. The classname is defined by
hibernate.search.filter.cache_strategy.
91
Chapter 5. Querying
This filter caching mechanism should not be confused with caching the actual filter
results. In Lucene it is common practice to wrap filters using the IndexReader around
a CachingWrapperFilter. The wrapper will cache the DocIdSet returned from the
getDocIdSet(IndexReader reader) method to avoid expensive recomputation. It is important
to mention that the computed DocIdSet is only cachable for the same IndexReader instance,
because the reader effectively represents the state of the index at the moment it was opened.
The document list cannot change within an opened IndexReader. A different/new IndexReader
instance, however, works potentially on a different set of Documents (either from a different index
or simply because the index has changed), hence the cached DocIdSet has to be recomputed.
Hibernate Search also helps with this aspect of caching. Per default the cache flag
of @FullTextFilterDef is set to FilterCacheModeType.INSTANCE_AND_DOCIDSETRESULTS
which will automatically cache the filter instance as well as wrap the
specified filter around a Hibernate specific implementation of CachingWrapperFilter
(org.hibernate.search.filter.CachingWrapperFilter). In contrast to Lucene's version
of this class SoftReferences are used together with a hard reference count (see
discussion about filter cache). The hard reference count can be adjusted using
hibernate.search.filter.cache_docidresults.size (defaults to 5). The wrapping behaviour
can be controlled using the @FullTextFilterDef.cache parameter. There are three different
values for this parameter:
Value Definition
FilterCacheModeType.NONE No filter instance and no result is cached by
Hibernate Search. For every filter call, a new
filter instance is created. This setting might
be useful for rapidly changing data sets or
heavily memory constrained environments.
FilterCacheModeType.INSTANCE_ONLY The filter instance is cached and reused
across concurrent Filter.getDocIdSet()
calls. DocIdSet results are not cached. This
setting is useful when a filter uses its own
specific caching mechanism or the filter
results change dynamically due to application
specific events making DocIdSet caching in
both cases unnecessary.
FilterCacheModeType.INSTANCE_AND_DOCIDSETRESULTS
Both the filter instance and the DocIdSet
results are cached. This is the default value.
Last but not least - why should filters be cached? There are two areas where filter caching shines:
• the system does not update the targeted entity index often (in other words, the IndexReader
is reused a lot)
• the Filter's DocIdSet is expensive to compute (compared to the time spent to execute the query)
92
Using filters in a sharded environment
Let's first look at an example of sharding strategy that query on a specific customer shard if the
customer filter is activated.
/**
* Optimization; don't search ALL shards and union the results; in this case, we
* can be certain that all the data for a particular customer Filter is in a single
* shard; simply return that shard by customerID.
*/
public DirectoryProvider<?>[]
getDirectoryProvidersForQuery(FullTextFilterImplementor[] filters) {
FFullTextFilter filter = getCustomerFilter(filters, "customer");
if (filter == null) {
93
Chapter 5. Querying
return getDirectoryProvidersForAllShards();
}
else {
return new DirectoryProvider[]
{ providers[Integer.parseInt(filter.getParameter("customerID").toString())] };
}
}
In this example, if the filter named customer is present, we make sure to only use the shard
dedicated to this customer. Otherwise, we return all shards. A given Sharding strategy can react
to one or more filters and depends on their parameters.
The second step is simply to activate the filter at query time. While the filter can be a regular filter
(as defined in Section 5.3, “Filters”) which also filters Lucene results after the query, you can make
use of a special filter that will only be passed to the sharding strategy and otherwise ignored for the
rest of the query. Simply use the ShardSensitiveOnlyFilter class when declaring your filter.
@Entity @Indexed
@FullTextFilterDef(name="customer", impl=ShardSensitiveOnlyFilter.class)
public class Customer {
...
}
Note that by using the ShardSensitiveOnlyFilter, you do not have to implement any Lucene
filter. Using filters and sharding strategy reacting to these filters is recommended to speed up
queries in a sharded environment.
94
Native Lucene Queries
• the number of object loaded: use pagination (always ;-) ) or index projection (if needed)
• the way Hibernate Search interacts with the Lucene readers: defines the appropriate Reader
strategy.
95
96
Chapter 6.
All these methods affect the Lucene Index only, no changes are applied to the Database.
In case you want to add all instances for a type, or for all indexed types, the recommended
approach is to use a MassIndexer: see Section 6.3.2, “Using a MassIndexer” for more details.
97
Chapter 6. Manual index changes
Purging will remove the entity with the given id from the Lucene index but will not touch the
database.
If you need to remove all entities of a given type, you can use the purgeAll method. This operation
removes all entities of the type passed as a parameter as well as all its subtypes.
Note
Note
All manual indexing methods (index, purge and purgeAll) only affect the index,
not the database, nevertheless they are transactional and as such they won't
be applied until the transaction is successfully committed, or you make use of
flushToIndexes.
• Use a MassIndexer.
98
Using flushToIndexes()
This strategy consists in removing the existing index and then adding all entities back to the
index using FullTextSession.purgeAll() and FullTextSession.index(), however there are
some memory and efficiency contraints. For maximum efficiency Hibernate Search batches index
operations and executes them at commit time. If you expect to index a lot of data you need
to be careful about memory consumption since all documents are kept in a queue until the
transaction commit. You can potentially face an OutOfMemoryException if you don't empty the
queue periodically: to do this you can use fullTextSession.flushToIndexes(). Every time
fullTextSession.flushToIndexes() is called (or if the transaction is committed), the batch
queue is processed applying all index changes. Be aware that, once flushed, the changes cannot
be rolled back.
fullTextSession.setFlushMode(FlushMode.MANUAL);
fullTextSession.setCacheMode(CacheMode.IGNORE);
transaction = fullTextSession.beginTransaction();
//Scrollable results will avoid loading too many objects in memory
ScrollableResults results = fullTextSession.createCriteria( Email.class )
.setFetchSize(BATCH_SIZE)
.scroll( ScrollMode.FORWARD_ONLY );
int index = 0;
while( results.next() ) {
index++;
fullTextSession.index( results.get(0) ); //index each element
if (index % BATCH_SIZE == 0) {
fullTextSession.flushToIndexes(); //apply changes to indexes
fullTextSession.clear(); //free memory since the queue is processed
}
}
transaction.commit();
Note
Try to use a batch size that guarantees that your application will not run out of memory: with a
bigger batch size objects are fetched faster from database but more memory is needed.
99
Chapter 6. Manual index changes
Hibernate Search's MassIndexer uses several parallel threads to rebuild the index; you can
optionally select which entities need to be reloaded or have it reindex all entities. This approach is
optimized for best performance but requires to set the application in maintenance mode: making
queries to the index is not recommended when a MassIndexer is busy.
fullTextSession.createIndexer().startAndWait();
This will rebuild the index, deleting it and then reloading all entities from the database. Although
it's simple to use, some tweaking is recommended to speed up the process: there are several
parameters configurable.
Warning
During the progress of a MassIndexer the content of the index is undefined, make
sure that nobody will try to make some query during index rebuilding! If somebody
should query the index it will not corrupt but most results will likely be missing.
fullTextSession
.createIndexer( User.class )
.batchSizeToLoadObjects( 25 )
.cacheMode( CacheMode.NORMAL )
.threadsToLoadObjects( 5 )
.threadsForSubsequentFetching( 20 )
.startAndWait();
This will rebuild the index of all User instances (and subtypes), and will create 5 parallel threads
to load the User instances using batches of 25 objects per query; these loaded User instances
are then pipelined to 20 parallel threads to load the attached lazy collections of User containing
some information needed for the index.
100
Using a MassIndexer
Tip
Note
The MassIndexer was designed for speed and is unaware of transactions, so there
is no need to begin one or committing. Also because it is not transactional it is not
recommended to let users use the system during it's processing, as it is unlikely
people will be able to find results and the system load might be too high anyway.
Other parameters which also affect indexing time and memory consumption are:
• hibernate.search.[default|<indexname>].exclusive_index_use
• hibernate.search.[default|<indexname>].indexwriter.batch.max_buffered_docs
• hibernate.search.[default|<indexname>].indexwriter.batch.max_field_length
• hibernate.search.[default|<indexname>].indexwriter.batch.max_merge_docs
• hibernate.search.[default|<indexname>].indexwriter.batch.merge_factor
• hibernate.search.[default|<indexname>].indexwriter.batch.ram_buffer_size
• hibernate.search.[default|<indexname>].indexwriter.batch.term_index_interval
All .indexwriter parameters are Lucene specific and Hibernate Search is just passing these
parameters through - see Section 3.9, “Tuning Lucene indexing performance” for more details.
101
102
Chapter 7.
Index Optimization
From time to time, the Lucene index needs to be optimized. The process is essentially a
defragmentation. Until an optimization is triggered Lucene only marks deleted documents as such,
no physical deletions are applied. During the optimization process the deletions will be applied
which also effects the number of files in the Lucene Directory.
Optimizing the Lucene index speeds up searches but has no effect on the indexation (update)
performance. During an optimization, searches can be performed, but will most likely be slowed
down. All index updates will be stopped. It is recommended to schedule optimization:
When using a MassIndexer (see Section 6.3.2, “Using a MassIndexer”) it will optimize involved
indexes by default at the start and at the end of processing; you can change this behavior by using
respectively MassIndexer.optimizeAfterPurge and MassIndexer.optimizeOnFinish.
The configuration for automatic index optimization can be defined on a global level or per index:
hibernate.search.default.optimizer.operation_limit.max = 1000
hibernate.search.default.optimizer.transaction_limit.max = 100
hibernate.search.Animal.optimizer.transaction_limit.max = 50
103
Chapter 7. Index Optimization
searchFactory.optimize(Order.class);
// or
searchFactory.optimize();
The first example optimizes the Lucene index holding Orders; the second, optimizes all indexes.
Note
searchFactory.optimize() has no effect on a JMS backend. You must apply
the optimize operation on the Master node.
• hibernate.search.[default|<indexname>].indexwriter.[batch|
transaction].max_buffered_docs
• hibernate.search.[default|<indexname>].indexwriter.[batch|
transaction].max_field_length
• hibernate.search.[default|<indexname>].indexwriter.[batch|
transaction].max_merge_docs
• hibernate.search.[default|<indexname>].indexwriter.[batch|
transaction].merge_factor
• hibernate.search.[default|<indexname>].indexwriter.[batch|
transaction].ram_buffer_size
• hibernate.search.[default|<indexname>].indexwriter.[batch|
transaction].term_index_interval
104
Adjusting optimization
See Section 3.9, “Tuning Lucene indexing performance” for more details.
105
106
Chapter 8.
Advanced features
8.1. SearchFactory
The SearchFactory object keeps track of the underlying Lucene resources for Hibernate Search,
it's also a convenient way to access Lucene natively. The SearchFactory can be accessed from
a FullTextSession:
DirectoryProvider[] provider =
searchFactory.getDirectoryProviders(Order.class);
org.apache.lucene.store.Directory directory = provider[0].getDirectory();
In this example, directory points to the lucene index storing Orders information. Note that the
obtained Lucene directory must not be closed (this is Hibernate Search responsibility).
DirectoryProvider orderProvider =
searchFactory.getDirectoryProviders(Order.class)[0];
107
Chapter 8. Advanced features
DirectoryProvider clientProvider =
searchFactory.getDirectoryProviders(Client.class)[0];
try {
//do read-only operations on the reader
}
finally {
readerProvider.closeReader(reader);
}
The ReaderProvider (described in Reader strategy), will open an IndexReader on top of the
index(es) referenced by the directory providers. Because this IndexReader is shared amongst
several clients, you must adhere to the following rules:
• Don't use this IndexReader for modification operations (you would get an exception). If you
want to use a read/write index reader, open one from the Lucene Directory object.
Aside from those rules, you can use the IndexReader freely, especially to do native queries. Using
the shared IndexReaders will make most queries more efficient.
Factor Description
tf(t ind) Term frequency factor for the term (t) in the
document (d).
idf(t) Inverse document frequency of the term.
coord(q,d) Score factor based on how many of the query
terms are found in the specified document.
queryNorm(q) Normalizing factor used to make scores
between queries comparable.
t.getBoost() Field boost.
norm(t,d) Encapsulates a few (indexing time) boost and
length factors.
108
Customizing Lucene's scoring formula
It is beyond the scope of this manual to explain this formula in more detail. Please refer to
Similarity's Javadocs for more information.
Hibernate Search provides two ways to modify Lucene's similarity calculation. First you can
set the default similarity by specifying the fully specified classname of your Similarity
implementation using the property hibernate.search.similarity. The default value is
org.apache.lucene.search.DefaultSimilarity. Additionally you can override the default
similarity on class level using the @Similarity annotation.
@Entity
@Indexed
@Similarity(impl = DummySimilarity.class)
public class Book {
...
}
As an example, let's assume it is not important how often a term appears in a document.
Documents with a single occurrence of the term should be scored the same as documents with
multiple occurrences. In this case your custom implementation of the method tf(float freq)
should return 1.0.
Warning
When two entities share the same index they must declare the same Similarity
implementation. Classes in the same class hierarchy always share the index, so
it's not allowed to override the Similarity implementation in a subtype.
109
110