Search code examples
elasticsearchhibernate-searchquarkus

How to search for query results which also match a filter in Hibernate search


I am using Hibernate Search 6, with an elastic search backend.
I am using the following to search the book titles.

Search.session(entityManager)
            .search(Book.class)
            .predicate(f -> query == null || query.trim().isEmpty() ? f.matchAll()
                    : f.simpleQueryString()
                        .field("title")
                        .matching(query))
            .fetchHits(10);  

Now my Book entity has a boolean field inStock. I would like my hibernate search results to include only those books where inStock is true. I could do a filter in java on the resultant list, but that would spoil the pagination and not be as elegant a solution as something in the query itself


Solution

  • Maybe something like this?

    Search.session(entityManager).search(Book.class)
            .predicate(f -> f.bool(b -> { 
                b.must(f.match().field("inStock").matching(true));
                if (query != null && !query.trim().isEmpty()) { 
                    b.must(f.simpleQueryString().field("title")
                            .matching(query));
                }
            }))
            .fetchHits(10);  
    

    Or, if "inStock" is passed as a parameter and may be null (to indicate "no constraint on the stock status"):

    Search.session(entityManager).search(Book.class)
            .predicate(f -> f.bool(b -> { 
                b.must(f.matchAll()); // Match everything by default, if there are no constraints
                if (inStock != null) {
                    b.must(f.match().field("inStock").matching(true));
                }
                if (query != null && !query.trim().isEmpty()) { 
                    b.must(f.simpleQueryString().field("title")
                            .matching(query));
                }
            }))
            .fetchHits(10);  
    

    See this section of the documentation, especially the last example ("Easily adding clauses dynamically with the lambda syntax")