如果userId为null,我想删除.withQuery(QueryBuilders.matchQuery(“createdBy”,userId))这个条件,如何根据我的传递参数动态实现搜索。
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;
}
答案 0 :(得分:0)
是的, matchQuery 不接受空值并抛出:
java.lang.IllegalArgumentException: [match] requires query value
NativeSearchQueryBuilder 是一个与任何其他对象一样的对象,因此您可以在进行一些额外准备后构建它。可能不是最漂亮的,但会做你想做的事:
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();