Home > Back-end >  Get document scores within Hibernate Search
Get document scores within Hibernate Search

Time:08-12

we query multiple indices but with different field names and merge the result into a global search. To add pagination, I want to use the scores by sorting the results by score and calculate the page myself.

My question is now: How to I get the score for each document? I saw that I can sort by score but not how the get the actual score value.

Any help is apreciated!

P.S. I'm using an Elasticsearch backend and hibernate search 6.1.5

CodePudding user response:

It's in the documentation: score projection.

List<Float> hits = searchSession.search( Book.class )
        .select( f -> f.score() )
        .where( f -> f.match().field( "title" )
                .matching( "robot dawn" ) )
        .fetchHits( 20 );

And if you want the entity and the score, use both the score projection and the entity projection, and combine them with a composite projection.

List<MyPair<Book, Float>> hits = searchSession.search( Book.class )
        .select( f -> f.composite( 
                MyPair::new, 
                f.entity(), 
                f.score() 
        ) )
        .where( f -> f.matchAll() )
        .fetchHits( 20 ); 

Note that Hibernate Search 6.2 (still in development) will introduce a slightly more explicit syntax:

List<MyPair<Book, Float>> hits = searchSession.search( Book.class )
        .select( f -> f.composite()
                .from( f.entity(), f.score() )
                .as( MyPair::new ) )
        .where( f -> f.matchAll() )
        .fetchHits( 20 ); 
  • Related