本文介绍了弹性搜索过滤文档按字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一些文件:
{"name": "John", "district": 1},
{"name": "Mary", "district": 2},
{"name": "Nick", "district": 1},
{"name": "Bob", "district": 3},
{"name": "Kenny", "district": 1}
如何按区划过滤/选择不同的文件?
How can I filter/select distinct documents by district?
{"name": "John", "district": 1},
{"name": "Mary", "district": 2},
{"name": "Bob", "district": 3}
在SQL中,我可以使用GROUP BY。我尝试了术语聚合,但只返回计数不同。
In SQL, I can use GROUP BY. I tried terms aggregation but it only returned count distinct.
"aggs": {
"distinct": {
"terms": {
"field": "district",
"size": 0
}
}
}
感谢您的帮助! : - )
Thank for your help! :-)
推荐答案
如果您的ElasticSearch版本为1.3或更高版本,则可以使用,这将给你(默认情况下)前三名匹配文件按您的查询分数排序(这里,1,当您使用match_all查询)。
If your ElasticSearch version is 1.3 or above, you could use a subaggregation of type top_hits which will give you (by default) the top three matching documents sorted on your query score (here, 1 as you use a match_all query).
您可以设置大小
参数超过3个。
You can set the size
parameter to more than 3.
以下数据集和查询:
POST /test/districts/
{"name": "John", "district": 1}
POST /test/districts/
{"name": "Mary", "district": 2}
POST /test/districts/
{"name": "Nick", "district": 1}
POST /test/districts/
{"name": "Bob", "district": 3}
POST test/districts/_search
{
"size": 0,
"aggs":{
"by_district":{
"terms": {
"field": "district",
"size": 0
},
"aggs": {
"tops": {
"top_hits": {
"size": 10
}
}
}
}
}
}
将以您想要的方式输出文档:
Will output the documents the way you want :
{
"took": 5,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total": 4,
"max_score": 0,
"hits": []
},
"aggregations": {
"by_district": {
"buckets": [
{
"key": 1,
"key_as_string": "1",
"doc_count": 2,
"tops": {
"hits": {
"total": 2,
"max_score": 1,
"hits": [
{
"_index": "test",
"_type": "districts",
"_id": "XYHu4I-JQcOfLm3iWjTiOg",
"_score": 1,
"_source": {
"name": "John",
"district": 1
}
},
{
"_index": "test",
"_type": "districts",
"_id": "5dul2XMTRC2IpV_tKRRltA",
"_score": 1,
"_source": {
"name": "Nick",
"district": 1
}
}
]
}
}
},
{
"key": 2,
"key_as_string": "2",
"doc_count": 1,
"tops": {
"hits": {
"total": 1,
"max_score": 1,
"hits": [
{
"_index": "test",
"_type": "districts",
"_id": "I-9Gd4OYSRuexhP1dCdQ-g",
"_score": 1,
"_source": {
"name": "Mary",
"district": 2
}
}
]
}
}
},
{
"key": 3,
"key_as_string": "3",
"doc_count": 1,
"tops": {
"hits": {
"total": 1,
"max_score": 1,
"hits": [
{
"_index": "test",
"_type": "districts",
"_id": "bti2y-OUT3q2mBNhhI3xeA",
"_score": 1,
"_source": {
"name": "Bob",
"district": 3
}
}
]
}
}
}
]
}
}
}
这篇关于弹性搜索过滤文档按字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!