Reputation: 117
if userId is null ,I want to remove .withQuery(QueryBuilders.matchQuery("createdBy",userId)) this condition, how can I implement search dynamically according to my passing parameters.
public <T> List<T> search(String index, String type, String tenantId ,String userId, String queryString, Class<T> clzz){
log.debug("==========search==========");
String allField = "_all";
MultiMatchQueryBuilder multiMatchQueryBuilder = QueryBuilders.multiMatchQuery(queryString, allField);
SearchQuery searchQuery = new NativeSearchQueryBuilder()
.withIndices(index)
.withTypes(type)
.withQuery(multiMatchQueryBuilder)
.withQuery(QueryBuilders.matchQuery("tenantId",tenantId))
.withQuery(QueryBuilders.matchQuery("createdBy",userId))
.build();
List<T> list =
operations.queryForPage(searchQuery,clzz).getContent();
return list;
}
Upvotes: 2
Views: 2248
Reputation: 2208
Right, matchQuery does not accept null value and throws:
java.lang.IllegalArgumentException: [match] requires query value
NativeSearchQueryBuilder is an object like any other so you can build it after some additional preparation. Probably not the prettiest, but will do what you want:
NativeSearchQueryBuilder nativeSearch = new NativeSearchQueryBuilder()
.withIndices(index)
.withTypes(type)
.withQuery(multiMatchQueryBuilder)
.withQuery(QueryBuilders.matchQuery("tenantId", tenantId));
if (userId != null) {
nativeSearch.withQuery(QueryBuilders.matchQuery("createdBy", userId));
}
SearchQuery searchQuery = nativeSearch.build();
Upvotes: 2