Elasticsearch 学习 4. Elasticsearch DSL搜索、高亮显示、聚合查询

一、DSL 查询

       Elasticsearch提供丰富且灵活的的查询语言叫做  DSL查询(Query DSL),它允许你构建更加复杂的查询,强大的查询。

       DSL(Domain Specific Language 特定领域语言)以JSON请求体的形式出现。

       示例:查询age=20岁的用户

原始数据展示

# 请求参数

POST http://localhost:9200/haoke/user/_search

{
	"query":{
		"match":{    #match只是查询的一种
			"age":20
		}
	}
}

#返回结果
{
    "took": 4,
    "timed_out": false,
    "_shards": {
        "total": 2,
        "successful": 2,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 1,
            "relation": "eq"
        },
        "max_score": 1,
        "hits": [
            {
                "_index": "haoke",
                "_type": "user",
                "_id": "LwPYcnEBK3PERGtNAOmn",
                "_score": 1,
                "_source": {
                    "id": 1002,
                    "name": "张三",
                    "age": 23,
                    "sex": "男"
                }
            }
        ]
    }
}

 #math: 只能作为 单条件查询,如果 有多个条件,则会报错,例如

{
	"query":{
		"match":{      # 两个条件时则会报错
			"age":23,
			"sex":"女"
		}
	}
}

# 报错信息

{
    "error": {
        "root_cause": [
            {
                "type": "parsing_exception",
                "reason": "[match] query doesn't support multiple fields, found [age] and [sex]",
                "line": 5,
                "col": 10
            }
        ],
        "type": "parsing_exception",
        "reason": "[match] query doesn't support multiple fields, found [age] and [sex]",
        "line": 5,
        "col": 10
    },
    "status": 400
}

示例:查询年龄(age)>20岁的用户

# 请求参数

POST http://localhost:9200/haoke/user/_search

{
	"query": {
		"bool": {
			"filter": {
				"range": {
					"age": {
						"gt": 20
					}
				}
			},
			"must": {
				"match": {
					"sex": "男"
				}
			}
		}
	}
}

# 返回结果
{
    "took": 5,
    "timed_out": false,
    "_shards": {
        "total": 2,
        "successful": 2,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 1,
            "relation": "eq"
        },
        "max_score": 0.6931472,
        "hits": [
            {
                "_index": "haoke",
                "_type": "user",
                "_id": "LwPYcnEBK3PERGtNAOmn",
                "_score": 0.6931472,
                "_source": {
                    "id": 1002,
                    "name": "张三",
                    "age": 23,
                    "sex": "男"
                }
            }
        ]
    }
}

二、 全文索搜

# 传入参数
POST http://localhost:9200/haoke/user/_search

{
	"query": {
		"match":{
			"name":"张三 王五"
		}
	}
}


# 返回结果
{
    "took": 41,
    "timed_out": false,
    "_shards": {
        "total": 2,
        "successful": 2,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 2,
            "relation": "eq"
        },
        "max_score": 1.3862944,
        "hits": [
            {
                "_index": "haoke",
                "_type": "user",
                "_id": "LgOccnEBK3PERGtN9-n7",
                "_score": 1.3862944,
                "_source": {
                    "name": "王五",
                    "age": 20,
                    "sex": "女"
                }
            },
            {
                "_index": "haoke",
                "_type": "user",
                "_id": "LwPYcnEBK3PERGtNAOmn",
                "_score": 1.3862944,
                "_source": {
                    "id": 1002,
                    "name": "张三",
                    "age": 23,
                    "sex": "男"
                }
            }
        ]
    }
}

三、高亮显示

# 传入参数  
POST http://localhost:9200/haoke/user/_search

{
	"query": {
		"match": {
			"name": "张三 李四"
		}
	},
	"highlight": {
		"fields": {
			"name": {}
		}
	}
}

# 返回结果

{
    "took": 164,
    "timed_out": false,
    "_shards": {
        "total": 2,
        "successful": 2,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 2,
            "relation": "eq"
        },
        "max_score": 1.3862944,
        "hits": [
            {
                "_index": "haoke",
                "_type": "user",
                "_id": "LwPYcnEBK3PERGtNAOmn",
                "_score": 1.3862944,
                "_source": {
                    "id": 1002,
                    "name": "张三",
                    "age": 23,
                    "sex": "男"
                },
                "highlight": {
                    "name": [
                        "<em>张</em><em>三</em>"      #高亮显示
                    ]
                }
            },
            {
                "_index": "haoke",
                "_type": "user",
                "_id": "MAPYcnEBK3PERGtNx-k7",
                "_score": 0.5753642,
                "_source": {
                    "id": 1003,
                    "name": "李四",
                    "age": 20,
                    "sex": "女"
                },
                "highlight": {
                    "name": [
                        "<em>李</em><em>四</em>"      #高亮显示
                    ]
                }
            }
        ]
    }
}

四、 聚合查询

在 Elasticsearch中,支持聚合操作,类似SQL中的group by 操作

# 请求参数

POST http://localhost:9200/haoke/user/_search

{
	"aggs":{
		"all_interests":{
			"terms":{
				"field":"age"
			}
		}
	}
}

# 返回结果
{
    "took": 61,
    "timed_out": false,
    "_shards": {
        "total": 2,
        "successful": 2,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 3,
            "relation": "eq"
        },
        "max_score": 1,
        "hits": [
            {
                "_index": "haoke",
                "_type": "user",
                "_id": "LgOccnEBK3PERGtN9-n7",
                "_score": 1,
                "_source": {
                    "name": "王五",
                    "age": 20,
                    "sex": "女"
                }
            },
            {
                "_index": "haoke",
                "_type": "user",
                "_id": "LwPYcnEBK3PERGtNAOmn",
                "_score": 1,
                "_source": {
                    "id": 1002,
                    "name": "张三",
                    "age": 23,
                    "sex": "男"
                }
            },
            {
                "_index": "haoke",
                "_type": "user",
                "_id": "MAPYcnEBK3PERGtNx-k7",
                "_score": 1,
                "_source": {
                    "id": 1003,
                    "name": "李四",
                    "age": 20,
                    "sex": "女"
                }
            }
        ]
    },
    "aggregations": {
        "all_interests": {
            "doc_count_error_upper_bound": 0,
            "sum_other_doc_count": 0,
            "buckets": [
                {
                    "key": 20,
                    "doc_count": 2     # 可以看出,年龄为20的用户有2个
                },
                {
                    "key": 23,
                    "doc_count": 1    # 可以看出,年龄为23的用户有1个
                }
            ]
        }
    }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
co.elastic.clients.elasticsearch.core.aggregations 是 Java 客户端 ElasticSearch 的一个聚合(Aggregation)方法,用于对数据进行分析和统计。 具体使用方法可以参考以下示例: ```java import co.elastic.clients.base.*; import co.elastic.clients.elasticsearch.*; import co.elastic.clients.elasticsearch.core.*; import co.elastic.clients.elasticsearch.core.aggregations.*; import co.elastic.clients.elasticsearch.core.aggregations.bucket.*; import co.elastic.clients.elasticsearch.core.aggregations.metrics.*; import java.io.IOException; import java.util.*; public class ElasticSearchAggregationExample { public static void main(String[] args) throws IOException, ApiException { RestClientBuilder restClientBuilder = RestClient.builder( new HttpHost("localhost", 9200, "http") ); ElasticSearch client = new ElasticSearch(restClientBuilder); SearchRequest request = new SearchRequest() .index("my_index") .source(new SearchSource() .query(new MatchAllQuery()) .aggregations(new TermsAggregation("my_terms_agg") .field("my_field") .size(10) .subAggregations(new AvgAggregation("my_avg_agg") .field("my_other_field") ) ) ); SearchResponse response = client.search(request); TermsAggregationResult myTermsAggResult = response.aggregations().terms("my_terms_agg"); for (TermsAggregationEntry entry : myTermsAggResult.buckets()) { String term = entry.keyAsString(); long count = entry.docCount(); AvgAggregationResult myAvgAggResult = entry.aggregations().avg("my_avg_agg"); double avg = myAvgAggResult.value(); System.out.println(term + ": " + count + ", avg: " + avg); } client.close(); } } ``` 这个例子展示了如何使用 co.elastic.clients.elasticsearch.core.aggregations 方法来进行聚合查询。在这个例子中,我们使用了 TermsAggregation 和 AvgAggregation 两个聚合方法,对数据进行了分组和统计。具体步骤为: 1. 创建一个 SearchRequest 对象,并设置索引名称和查询条件。 2. 在查询条件中添加聚合条件。这里使用了 TermsAggregation 来对数据进行分组,然后使用 AvgAggregation 来统计每个分组的平均值。 3. 执行查询,并获取查询结果。 4. 使用聚合结果对象的方法来获取聚合结果,然后对结果进行处理。 需要注意的是,聚合方法的具体参数和用法可以参考 ElasticSearch 官方文档。同时,Java 客户端的版本和 ElasticSearch 的版本也需要匹配,否则可能会出现兼容性问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值