Hibernate apache lucene based full text search with one static filter

206 views Asked by At

my goal is search only in active items here is my code snippet:

 FullTextEntityManager fullTextEntityManager =
            Search.getFullTextEntityManager(this.getEntityManager());

    QueryBuilder queryBuilder =
        fullTextEntityManager.getSearchFactory()
        .buildQueryBuilder()
        .forEntity(Myclass.class)
        .get();

    BooleanJunction<BooleanJunction> booleanJunction = queryBuilder.bool();

    for(String token : tokens){
        booleanJunction.should( queryBuilder.keyword()
            .wildcard()
            .onFields("field1", "field2", "field3")
            .matching(token + "*")
            .createQuery());
    }

    FullTextQuery jpaQuery = fullTextEntityManager.createFullTextQuery(booleanJunction.createQuery(), MyClass.class);

I want to filter with field4 which is Object,Enum, I have try this:

booleanJunction.must( queryBuilder.keyword()
            .wildcard()
            .onField("field4")
            .matching(Status.ACTIVE)
            .createQuery());

Status object is Enum.

in this case if the upper should not find anything result is all active items , it happens because it is bool query..

any suggestion?

1

There are 1 answers

0
femtoRgon On BEST ANSWER

If I understand correctly, you want a query someting like:

+(token1* token2* token3*) +field4:active

To build that, you don't want to add the field4:active part to the same boolean query as the set of tokens, you'll want to create a parent boolean query to add the set of token queries as a required (must) query. Something like:

BooleanJunction<BooleanJunction> parentJunction = queryBuilder.bool();
parentJunction.must(booleanJunction.createQuery());
parentJunction.must(field4activeQuery);