//起手构建请求 SearchRequest request = new SearchRequest();
request常用操作:
- 指定索引,可传入多个索引,支持通配符*
request.indices(String[] tables) 等同于 select xx from table1,table2…
//构建查询 SearchSourceBuilder builder = new SearchSourceBuilder();
builder常用操作:
- 分页查询
builder.from(0) builder.size(10) 等同于 limit 1,10 - 排序
builder.sort(“age”, SortOrder.DESC) 等同于 order by age desc - 过滤字段
String[] includes = {“name”}; String[] excludes = {}; query3.fetchSource(includes, excludes); 等同于 select name from index
//给SearchSourceBuilder设置查询条件
-
builder.query(QueryBuilder queryBuilder); // 聚合查询操作 -
builder.aggregation(AggregationBuilder aggregation); 常用QueryBuilder :
- QueryBuilders.matchAllQuery() 等同于 select * from index
- QueryBuilders.matchQuery() 等同于 select * from index where xxx
- QueryBuilders.boolQuery() 布尔类型查询,可传入多个各种QueryBuilder,构建更复杂的查询,每个QueryBuilder 相当于加了个()
- QueryBuilders.rangeQuery() 范围查询 等同于 where flied < and > filed
- QueryBuilders.fuzzyQuery() 模糊查询 .fuzziness() 函数指定模糊字符偏移量
常用AggregationBuilder :
- AggregationBuilders.max(“maxAge”).field(“age”); 最大值,等同于函数 select max(“age”) as maxAge
- AggregationBuilders.terms(“ageGroup”).field(“age”); 分组查询,等同于 group by age
QueryBuilders.boolQuery()常用函数:
1. 多个must(QueryBuilder) 等同于 ( QueryBuilder1 ) and ( QueryBuilder2 ) 多个must 取 ∩ 交集
2. 多个should(QueryBuilder) 等同于 ( QueryBuilder1 ) or ( QueryBuilder2 ) 多个should 取 ∪ 并集
3. 单个must/should 等同于 where xx = xx,单个must/should传入的QueryBuilder,符合这个条件
//must -> SQL ‘=’ ‘and’
boolQueryBuilder.must(QueryBuilders.matchQuery("age", "24"));
//should -> SQL ‘or’
boolQueryBuilder.should(QueryBuilders.matchQuery("age", "24"));
boolQueryBuilder.should(QueryBuilders.matchQuery("age", "25"));
QueryBuilders.rangeQuery()常用函数:
4. rangeQuery.gte("25"); 大于,对于指定字段进行大小判断
5. rangeQuery.lte("30"); 小于,对于指定字段进行大小判断
request.source(query);
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
|