如果您ElasticSearch版本是1.3或更高版本做到這一點,你可以使用top_hits型subaggregation這會給你(默認情況下)排序在你的查詢分數上的前三個匹配文檔(在你使用match_all查詢時,這裏是1)。
您可以將size
參數設置爲超過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
}
}
}
}
}
}
將輸出文件你想要的方式:
{
"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
}
}
]
}
}
}
]
}
}
}
難道我的答案解決您的問題 – 2014-09-23 04:51:31