Search code examples
hibernate-search

hibernate search check predicate per hit


I do something like this in hibernate search 6.2 with lucene backend:

final var searchSession = Search.session(em);
final var orgas = searchSession
  .search(Organization.class)
  .where(...)
  .hits();

Now I want to know per hit if a predicate p is true or not. I have the following approaches in mind.

  1. Get the result of the predicate as part of the query above. This would be nice, but I don't know how? Is this possible?

  2. Search again for Organization.class with a where that must match the ids of the previous hits and also the predicate. I can then lookup if an organization is part of that result as well and thereby know if the predicate is true or not. But it feels odd to match by id and run two queries.

  3. Execute the exact same search again but with the added predicate. Compared to the previous approach that would get rid of matching by id, but needs to execute the original (much more complex) query twice and it messes up pagination.

What is a good solution to this?


Solution

  • You can also take a look at using score and bool predicate. You can put the predicate you want to "check" as a should clause, and use filter to limit the results to whatever you currently use in the where clause. That'll look something like:

    .search(Organization.class)
    .select( f -> f.composite().from(
            f.score(),
            f.id(),
            ...
    ).asList() )
    .where( f -> f.bool()
            // this predicate will be used for scoring the hits.
            // if the score == 0 that would mean the predicate didn't match
            .should( your predicate p )
            // you will only get the same results as you are getting now: 
            .filter( your current where predicate )
    )
    

    filter in bool operator will perform filtering and you only would get the results matching the predicate from that filter. And should predicate will be used for scoring the hits. Here's a link to bool predicate documentation for any additional info.