来自:blog.csdn.net/mu_wind/article/details/118423362
测试使用的数据示例
{
"_index" : "person",
"_type" : "_doc",
"_id" : "4",
"_score" : 1.0,
"_source" : {
"address" : "峨眉山",
"modifyTime" : "2021-06-29 19:46:25",
"createTime" : "2021-05-14 11:37:07",
"sect" : "峨嵋派",
"sex" : "男",
"skill" : "降龙十八掌",
"name" : "宋青书",
"id" : 4,
"power" : 50,
"age" : 21
}
}
1 词条查询
1.1 等值查询-term
select * from person where name = '张无忌';
GET /person/_search
{
"query": {
"term": {
"name.keyword": {
"value": "张无忌",
"boost": 1.0
}
}
}
}
{
"took" : ,
"timed_out" : false,
"_shards" : { // 分片信息
"total" : 1, // 总计分片数
"successful" : 1, // 查询成功的分片数
"skipped" : , // 跳过查询的分片数
"failed" : // 查询失败的分片数
},
"hits" : { // 命中结果
"total" : {
"value" : 1, // 数量
"relation" : "eq" // 关系:等于
},
"max_score" : 2.8526313, // 高分数
"hits" : [
{
"_index" : "person", // 索引
"_type" : "_doc", // 类型
"_id" : "1",
"_score" : 2.8526313,
"_source" : {
"address" : "光明顶",
"modifyTime" : "2021-06-29 16:48:56",
"createTime" : "2021-05-14 16:50:33",
"sect" : "明教",
"sex" : "男",
"skill" : "九阳神功",
"name" : "张无忌",
"id" : 1,
"power" : 99,
"age" : 18
}
}
]
}
}
/**
* term查询
*
* @throws IOException
*/
@Autowired
private RestHighLevelClient client;
@Test
public void queryTerm() throws IOException {
// 根据索引创建查询请求
SearchRequest searchRequest = new SearchRequest("person");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
// 构建查询语句
searchSourceBuilder.query(QueryBuilders.termQuery("name.keyword", "张无忌"));
System.out.println("searchSourceBuilder=====================" + searchSourceBuilder);
searchRequest.source(searchSourceBuilder);
SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
System.out.println(JSONObject.toJSON(response));
}
_score
这一项,ES会根据结果匹配程度进行评分。打分是会耗费性能的,如果确认自己的查询不需要评分,就设置查询语句关闭评分:GET /person/_search
{
"query": {
"constant_score": {
"filter": {
"term": {
"sect.keyword": {
"value": "张无忌",
"boost": 1.0
}
}
},
"boost": 1.0
}
}
}
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
// 这样构造的查询条件,将不进行score计算,从而提高查询效率
searchSourceBuilder.query(QueryBuilders.constantScoreQuery(QueryBuilders.termQuery("sect.keyword", "明教")));
1.2 多值查询-terms
select * from persons where sect in('明教','武当派');
GET /person/_search
{
"query": {
"terms": {
"sect.keyword": [
"明教",
"武当派"
],
"boost": 1.0
}
}
}
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
// 构建查询语句
searchSourceBuilder.query(QueryBuilders.termsQuery("sect.keyword", Arrays.asList("明教", "武当派")));
}
1.3 范围查询-range
select * from pesons where age between 18 and 22;
GET /person/_search
{
"query": {
"range": {
"age": {
"from": 10,
"to": 20,
"include_lower": true,
"include_upper": true,
"boost": 1.0
}
}
}
}
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
// 构建查询语句
searchSourceBuilder.query(QueryBuilders.rangeQuery("age").gte(10).lte(30));
}
1.4 前缀查询-prefix
select * from persons where sect like '武当%';
{
"query": {
"prefix": {
"sect.keyword": {
"value": "武当",
"boost": 1.0
}
}
}
}
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
// 构建查询语句
searchSourceBuilder.query(QueryBuilders.prefixQuery("sect.keyword","武当"));
1.5 通配符查询-wildcard
select * from persons where name like '张%忌';
{
"query": {
"wildcard": {
"sect.keyword": {
"wildcard": "张*忌",
"boost": 1.0
}
}
}
}
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
// 构建查询语句
searchSourceBuilder.query(QueryBuilders.wildcardQuery("sect.keyword","张*忌"));
2 复合查询
select * from persons where sex = '女' and sect = '明教';
{
"query": {
"bool": {
"must": [
{
"term": {
"sex": {
"value": "女",
"boost": 1.0
}
}
},
{
"term": {
"sect.keywords": {
"value": "明教",
"boost": 1.0
}
}
}
],
"adjust_pure_negative": true,
"boost": 1.0
}
}
}
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
// 构建查询语句
searchSourceBuilder.query(QueryBuilders.boolQuery()
.must(QueryBuilders.termQuery("sex", "女"))
.must(QueryBuilders.termQuery("sect.keyword", "明教"))
);
2.1 布尔查询
{
"bool" : {
"must" : [],
"should" : [],
"must_not" : [],
}
}
must:所有的语句都必须匹配,与 ‘=’ 等价。 must_not:所有的语句都不能匹配,与 ‘!=’ 或 not in 等价。 should:至少有n个语句要匹配,n由参数控制。
must_not
语句都必须不匹配,但有多少 should 语句应该匹配呢?默认情况下,没有 should 语句是必须匹配的,只有一个例外:那就是当没有 must 语句的时候,至少有一个 should 语句必须匹配。minimum_should_match
参数控制需要匹配的 should 语句的数量,它既可以是一个的数字,又可以是个百分比:GET /person/_search
{
"query": {
"bool": {
"must": [
{
"term": {
"sex": {
"value": "女",
"boost": 1.0
}
}
}
],
"should": [
{
"term": {
"address.keyword": {
"value": "峨眉山",
"boost": 1.0
}
}
},
{
"term": {
"sect.keyword": {
"value": "明教",
"boost": 1.0
}
}
}
],
"adjust_pure_negative": true,
"minimum_should_match": "1",
"boost": 1.0
}
}
}
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
// 构建查询语句
searchSourceBuilder.query(QueryBuilders.boolQuery()
.must(QueryBuilders.termQuery("sex", "女"))
.should(QueryBuilders.termQuery("address.word", "峨眉山"))
.should(QueryBuilders.termQuery("sect.keyword", "明教"))
.minimumShouldMatch(1)
);
select
*
from
persons
where
sex = '女'
and
age between 30 and 40
and
sect != '明教'
and
(address = '峨眉山' OR skill = '暗器')
GET /person/_search
{
"query": {
"bool": {
"must": [
{
"term": {
"sex": {
"value": "女",
"boost": 1.0
}
}
},
{
"range": {
"age": {
"from": 30,
"to": 40,
"include_lower": true,
"include_upper": true,
"boost": 1.0
}
}
}
],
"must_not": [
{
"term": {
"sect.keyword": {
"value": "明教",
"boost": 1.0
}
}
}
],
"should": [
{
"term": {
"address.keyword": {
"value": "峨眉山",
"boost": 1.0
}
}
},
{
"term": {
"skill.keyword": {
"value": "暗器",
"boost": 1.0
}
}
}
],
"adjust_pure_negative": true,
"minimum_should_match": "1",
"boost": 1.0
}
}
}
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
// 构建查询语句
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery()
.must(QueryBuilders.termQuery("sex", "女"))
.must(QueryBuilders.rangeQuery("age").gte(30).lte(40))
.mustNot(QueryBuilders.termQuery("sect.keyword", "明教"))
.should(QueryBuilders.termQuery("address.keyword", "峨眉山"))
.should(QueryBuilders.rangeQuery("power.keyword").gte(50).lte(80))
.minimumShouldMatch(1); // 设置should至少需要满足几个条件
// 将BoolQueryBuilder构建到SearchSourceBuilder中
searchSourceBuilder.query(boolQueryBuilder);
2.2 Filter查询
{
"query": {
"bool": {
"filter": [
{
"term": {
"sex": {
"value": "男",
"boost": 1.0
}
}
}
],
"adjust_pure_negative": true,
"boost": 1.0
}
}
}
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
// 构建查询语句
searchSourceBuilder.query(QueryBuilders.boolQuery()
.filter(QueryBuilders.termQuery("sex", "男"))
);
select * from (select * from persons where sect = '明教')) a where sex = '女';
{
"query": {
"bool": {
"must": [
{
"term": {
"sect.keyword": {
"value": "明教",
"boost": 1.0
}
}
}
],
"filter": [
{
"term": {
"sex": {
"value": "女",
"boost": 1.0
}
}
}
],
"adjust_pure_negative": true,
"boost": 1.0
}
}
}
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
// 构建查询语句
searchSourceBuilder.query(QueryBuilders.boolQuery()
.must(QueryBuilders.termQuery("sect.keyword", "明教"))
.filter(QueryBuilders.termQuery("sex", "女"))
);
{
"query": {
"bool": {
"filter": [
{
"bool": {
"must": [
{
"term": {
"sect.keyword": {
"value": "明教",
"boost": 1.0
}
}
},
{
"range": {
"age": {
"from": 20,
"to": 35,
"include_lower": true,
"include_upper": true,
"boost": 1.0
}
}
}
],
"must_not": [
{
"term": {
"sex.keyword": {
"value": "女",
"boost": 1.0
}
}
}
],
"adjust_pure_negative": true,
"boost": 1.0
}
}
],
"adjust_pure_negative": true,
"boost": 1.0
}
}
}
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
// 构建查询语句
searchSourceBuilder.query(QueryBuilders.boolQuery()
.filter(QueryBuilders.boolQuery()
.must(QueryBuilders.termQuery("sect.keyword", "明教"))
.must(QueryBuilders.rangeQuery("age").gte(20).lte(35))
.mustNot(QueryBuilders.termQuery("sex.keyword", "女")))
);
3 聚合查询
3.1 值、平均值、求和
select max(age) from persons;
GET /person/_search
{
"aggregations": {
"max_age": {
"max": {
"field": "age"
}
}
}
}
@Autowired
private RestHighLevelClient client;
@Test
public void maxQueryTest() throws IOException {
// 聚合查询条件
AggregationBuilder aggBuilder = AggregationBuilders.max("max_age").field("age");
SearchRequest searchRequest = new SearchRequest("person");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
// 将聚合查询条件构建到SearchSourceBuilder中
searchSourceBuilder.aggregation(aggBuilder);
System.out.println("searchSourceBuilder----->" + searchSourceBuilder);
searchRequest.source(searchSourceBuilder);
// 执行查询,获取SearchResponse
SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
System.out.println(JSONObject.toJSON(response));
}
GET /person/_search
{
"size": 20,
"aggregations": {
"max_age": {
"max": {
"field": "age"
}
}
}
}
searchSourceBuilder.size(20);
AggregationBuilder minBuilder = AggregationBuilders.min("min_age").field("age");
AggregationBuilder avgBuilder = AggregationBuilders.avg("min_age").field("age");
AggregationBuilder sumBuilder = AggregationBuilders.sum("min_age").field("age");
AggregationBuilder countBuilder = AggregationBuilders.count("min_age").field("age");
3.2 去重查询
select count(distinct sect) from persons;
{
"aggregations": {
"sect_count": {
"cardinality": {
"field": "sect.keyword"
}
}
}
}
@Test
public void cardinalityQueryTest() throws IOException {
// 创建某个索引的request
SearchRequest searchRequest = new SearchRequest("person");
// 查询条件
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
// 聚合查询
AggregationBuilder aggBuilder = AggregationBuilders.cardinality("sect_count").field("sect.keyword");
searchSourceBuilder.size();
// 将聚合查询构建到查询条件中
searchSourceBuilder.aggregation(aggBuilder);
System.out.println("searchSourceBuilder----->" + searchSourceBuilder);
searchRequest.source(searchSourceBuilder);
// 执行查询,获取结果
SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
System.out.println(JSONObject.toJSON(response));
}
3.3 分组聚合
3.3.1 单条件分组
select sect,count(id) from mytest.persons group by sect;
{
"size": ,
"aggregations": {
"sect_count": {
"terms": {
"field": "sect.keyword",
"size": 10,
"min_doc_count": 1,
"shard_min_doc_count": ,
"show_term_doc_count_error": false,
"order": [
{
"_count": "desc"
},
{
"_key": "asc"
}
]
}
}
}
}
SearchRequest searchRequest = new SearchRequest("person");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.size();
// 按sect分组
AggregationBuilder aggBuilder = AggregationBuilders.terms("sect_count").field("sect.keyword");
searchSourceBuilder.aggregation(aggBuilder);
3.3.2 多条件分组
select sect,sex,count(id) from mytest.persons group by sect,sex;
{
"aggregations": {
"sect_count": {
"terms": {
"field": "sect.keyword",
"size": 10
},
"aggregations": {
"sex_count": {
"terms": {
"field": "sex.keyword",
"size": 10
}
}
}
}
}
}
3.4 过滤聚合
select max(age) from mytest.persons where sect = '明教';
GET /person/_search
{
"query": {
"term": {
"sect.keyword": {
"value": "明教",
"boost": 1.0
}
}
},
"aggregations": {
"max_age": {
"max": {
"field": "age"
}
}
}
}
SearchRequest searchRequest = new SearchRequest("person");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
// 聚合查询条件
AggregationBuilder maxBuilder = AggregationBuilders.max("max_age").field("age");
// 等值查询
searchSourceBuilder.query(QueryBuilders.termQuery("sect.keyword", "明教"));
searchSourceBuilder.aggregation(maxBuilder);
select
sum(case when age<=20 then 1 else end) ageGroup1,
sum(case when age >20 and age <=40 then 1 else end) ageGroup2,
sum(case when age >40 and age <=60 then 1 else end) ageGroup3,
sum(case when age >60 and age <=200 then 1 else end) ageGroup4
from
mytest.persons;
{
"size": ,
"aggregations": {
"age_avg": {
"range": {
"field": "age",
"ranges": [
{
"from": 0.0,
"to": 20.0
},
{
"from": 21.0,
"to": 40.0
},
{
"from": 41.0,
"to": 60.0
},
{
"from": 61.0,
"to": 200.0
}
],
"keyed": false
}
}
}
}
"aggregations" : {
"age_avg" : {
"buckets" : [
{
"key" : "0.0-20.0",
"from" : 0.0,
"to" : 20.0,
"doc_count" : 3
},
{
"key" : "21.0-40.0",
"from" : 21.0,
"to" : 40.0,
"doc_count" : 13
},
{
"key" : "41.0-60.0",
"from" : 41.0,
"to" : 60.0,
"doc_count" : 4
},
{
"key" : "61.0-200.0",
"from" : 61.0,
"to" : 200.0,
"doc_count" : 1
}
]
}
}