javaspring-boothibernate-search

How to construct dynamic queries with Hibernate Search 7?


I'm looking to construct dynamic queries with Hibernate Search 7.

I have an entity with multiple fields, and a search feature with optional fields. If an optional field is filled, I want to add a certain match criterion to the where clause.

I know how "fixed" field searching goes:

searchSession.search(Entity.class).where(entity -> {
    return entity.match().field("fieldName").matching(fieldValue);
})

However, I'm looking to do something along the lines of:

searchSession.search(Entity.class).where(entity -> {
    if(fieldValue1Exists){
        entity.match().field("fieldName1").matching(fieldValue1);
    }
    if(fieldValue2Exists){
        entity.match().field("fieldName2").matching(fieldValue2);
    }

    return entity.build(); // .build is not a method, just an example
})

How should I do this?


Solution

  • What you are looking for can be achieved with the dynamic boolean predicate:

    searchSession.search(Entity.class).where((f,root) -> {
        if(fieldValue1Exists){
            root.add(f.match().field("fieldName1").matching(fieldValue1));
        }
        if(fieldValue2Exists){
            root.add(f.match().field("fieldName2").matching(fieldValue2));
        }
    })
    

    it creates a bool operator where classes added through the .add(..) are treated as must clauses. See https://docs.jboss.org/hibernate/stable/search/reference/en-US/html_single/#search-dsl-predicate-boolean-lambda for a more detailed example.