调用client查询数据,使用SearchRequest对象处理操作 ,使用的建造者Builder模式添加插叙条件:
SearchRequest searchRequest = new SearchRequest(index);
searchRequest.types(type);
searchRequest.source(sourceBuilder);
SearchResponse response = client.search(searchRequest).get();
bool过滤可以用来合并多个过滤条件查询结果布尔逻辑,它包括一个操作符:
must 多个查询条件的完全匹配,相当于and。
must_not 多个查询条件的相反匹配,相当于not。
should 至少有一个查询条件匹配,相当于or。
对应的 BoolQueryBuilder 对象。
TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "张三");;
BoolQueryBuilder boolBuilderTemp = QueryBuilders.boolQuery();
boolBuilderTemp.should(termQueryBuilder);
boolBuilderTemp.must(termQueryBuilder);
boolBuilderTemp.mustNot(termQueryBuilder);
TermQueryBuilder对象处理 name = '张三' ,
TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "张三");
WildcardQueryBuilder 对象处理 name like '%张%' ,r
StringBuilder matchValue = new StringBuilder();
matchValue.append("*").append("张三").append("*");
WildcardQueryBuilder wildcardQueryBuilder = QueryBuilders.wildcardQuery("name",matchValue.toString());
WildcardQueryBuilder 处理范围查询 例如查询分数 score字段
RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("score");
// 小于等于 <=
rangeQueryBuilder.lte("10");
// 小于 <
rangeQueryBuilder.lt("10");
//大于 >
rangeQueryBuilder.gt("10");
// 大于等于 >=
rangeQueryBuilder.gte("10");
// between 10 and 100
rangeQueryBuilder.from("10");
rangeQueryBuilder.to("100");
查询数据排序SearchSourceBuilder对象
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.sort("createDate", SortOrder.ASC);
数据分页 SearchSourceBuilder对象的from方法设置起始位置,size方式设置显示的个数,可以实现数据分页。
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
// 起始条数
searchSourceBuilder.from(1);
// 显示数据条数
searchSourceBuilder.size(20);
最后将bool 和 queryBuilder 组合后形成完整sql
select * from table where name like '%张%' and score > 90 or level = 'A'
order by createDate desc limit 10 20;
// name like '%张%'
WildcardQueryBuilder matchQueryBuilder = QueryBuilders.wildcardQuery("name", "*张*");
// score > 90
RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("score");
rangeQuery.gt(90);
// level = 'A'
TermQueryBuilder termQuery = QueryBuilders.termQuery("level", "A");
BoolQueryBuilder boolBuilder = QueryBuilders.boolQuery();
boolBuilder.must(matchQueryBuilder); // name like '%张%' and
boolBuilder.must(rangeQuery); // score > 90
boolBuilder.should(termQuery);// or level = 'A'
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
// limit 10 20
sourceBuilder.from(10);
sourceBuilder.size(10);
// order by createDate desc
sourceBuilder.sort("createDate", SortOrder.DESC);
//添加查询对象
sourceBuilder.query(boolBuilder);
try {
//查询索引对象
SearchRequest searchRequest = new SearchRequest(index);
searchRequest.types(type);
searchRequest.source(sourceBuilder);
SearchResponse response = client.search(searchRequest).get();
System.out.println(response);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}