Is there a preferred way in the predicate DSL to match any in a list of enums? This is to match a state field that is annotated as @GenericField. In the search form, the users can select on one or more states to match. I see for .id() there is the concept of matchingAny, but I don’t see that available for anything else. Is this correct? Is so, what is the preferred method? I could build a SimpleQueryString or dynamically construct a must with a series of shoulds, etc. Thanks, Keith
There is no built-in matchingAny
for non-id predicates for now, so the preferred method would be this:
List<StateEnum> toMatchList = ...;
List<MyEntity> hits = Search.session(entityManager).search(MyEntity.class)
.where(f -> f.bool(b -> {
for(StateEnum toMatch : toMatchList) {
b.should(f.match().field("state").matching(toMatch));
}
})
.fetchHits(20);
You can make a small utility function if you need this in many places in your code:
public class SearchUtils {
private SearchUtils() {
}
public static SearchPredicate matchAny(SearchPredicateFactory f, String field, Collection<?> values) {
return f.bool(b -> {
for(Object toMatch : values) {
b.should(f.match().field(field).matching(toMatch));
}
})
.toPredicate();
}
}
Then use it like this:
List<StateEnum> toMatchList = ...;
List<MyEntity> hits = Search.session(entityManager).search(MyEntity.class)
.where(f -> SearchUtils.matchAny(f, "state", toMatch))
.fetchHits(20);
Thank you very much for the link and the suggestion. Works great.
To anyone ending up here looking for a solution: