[英]How to perform complex query on aggregated fields in ElasticSearch
[英]ElasticSearch: Access outer document fields from within an nested aggregated query
我有以下映射:
{
"dynamic": "strict",
"properties": {
"id": {
"type": "string"
},
"title": {
"type": "string"
},
"things": {
"type": "nested",
"properties": {
"id": {
"type": "long"
},
"something": {
"type": "long"
}
}
}
}
}
我將文檔插入如下(Python腳本):
body = {"id": 1, "title": "one", "things": [{"id": 1000, "something": 33}, {"id": 1001, "something": 34}, ]}
es.create(index_name, doc_type=doc_type, body=body, id=1)
body = {"id": 2, "title": "two", "things": [{"id": 1000, "something": 43}, {"id": 1001, "something": 44}, ]}
es.create(index_name, doc_type=doc_type, body=body, id=2)
body = {"id": 3, "title": "three", "things": [{"id": 1000, "something": 53}, {"id": 1001, "something": 54}, ]}
es.create(index_name, doc_type=doc_type, body=body, id=3)
我運行以下聚合查詢:
{
"query": {
"match_all": {}
},
"aggs": {
"things": {
"aggs": {
"num_articles": {
"terms": {
"field": "things.id",
"size": 0
},
"aggs": {
"articles": {
"top_hits": {
"size": 50
}
}
}
}
},
"nested": {
"path": "things"
}
}
},
"size": 0
}
(因此,我希望計數每個“事物”出現的次數,並針對每個事物列出出現每個事物的文章列表)
查詢產生:
"key": 1000,
"doc_count": 3,
"articles": {
"hits": {
"total": 3,
"max_score": 1,
"hits": [{
"_index": "test",
"_type": "article",
"_id": "2",
"_nested": {
"field": "things",
"offset": 0
},
"_score": 1,
"_source": {
"id": 1000,
"something": 43
}
}, {
"_index": "test",
"_type": "article",
"_id": "1",
"_nested": {
"field": "things",
"offset": 0
},
"_score": 1,
"_source": {
"id": 1000,
"something": 33
}
.... (等等)
我想要的是讓每個匹配項列出“外部”或頂級文檔中的所有字段,例如ID和標題。
這實際上可能嗎...如果是這樣的話???
我不確定這是否是您要尋找的東西,但讓我們嘗試一下:
{
"query": {
"match_all": {}
},
"aggs": {
"nested_things": {
"nested": {
"path": "things"
},
"aggs": {
"num_articles": {
"terms": {
"field": "things.id",
"size": 0
},
"aggs": {
"articles": {
"top_hits": {
"size": 50
}
},
"reverse_things": {
"reverse_nested": {},
"aggs": {
"title": {
"terms": {
"field": "title",
"size": 0
}
},
"id": {
"terms": {
"field": "id",
"size": 0
}
}
}
}
}
}
}
}
}
}
這將產生如下內容:
"buckets": [
{
"key": 1000,
"doc_count": 3,
"reverse_things": {
"doc_count": 3,
"id": {
"buckets": [
{
"key": "1",
"doc_count": 1
},
{
"key": "2",
"doc_count": 1
},
{
"key": "3",
"doc_count": 1
}
]
},
"title": {
...
}
},
"articles": {
"hits": {
"total": 3,
"max_score": 1,
"hits": [
{
"_index": "test",
"_type": "article",
"_id": "AVPOgQQjgDGxUAMojyuY",
"_nested": {
"field": "things",
"offset": 0
},
"_score": 1,
"_source": {
"id": 1000,
"something": 53
}
},
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.