2020-03-21

Hibernate Search - Routing

If a search query already uses predicates to filter documents in such a way that all matching documents will have a routing key in a known subset of all possible routing keys, it is possible to specify these routing keys to Hibernate Search so that only the relevant shards are queried, potentially improving performance.

Specifying routing keys is done by calling the .routing(String) or .routing(Collection<String>) methods when building the query:


Routing a query to a subset of all shards

SearchResult<Book> result = searchSession.search( Book.class ) 
        .where( f -> f.match()
                .field( "genre" )
                .matching( Genre.SCIENCE_FICTION ) ) 
        .routing( Genre.SCIENCE_FICTION.name() ) 
        .fetch( 20 ); 

Start building the query.
Define that only documents matching the given genre should be returned.
In this case, the entity is mapped in such a way that the genre is also used as a routing key. We know all documents will have the given genre value, so we can specify the routing key to limit the query to relevant shards.
Build the query and fetch the results.

No comments:

Post a Comment