[英]How to perform aggregation (eg. avg) on list of objects in Elasticsearch?
我在 Elasticsearch 中有以下形式的數據:
[
{
"id": 1,
"name": "abc",
"score": 10,
"values": [
{
"v1": 1,
"v2": 2
}
]
},
{
"id": 2,
"name": "def",
"score": 20,
"values": [
{
"v1": 3,
"v2": 4
}
]
}
]
目前,我正在使用以下代碼計算平均score
:
s = Search(using=es, index=index).query(Q(query))
s.aggs.bucket('average_score', 'avg', field='score') # average_score = 15
現在我希望使用elasticsearch_dsl
計算v1
和v2
平均值,但我不知道如何進行嵌套聚合。 在本例中, v1 = 2
和v2 = 3
。 請幫忙。 提前致謝!
編輯:不幸的是,這里的values
是一個對象而不是嵌套的。
不知道如何在你的 DSL 中做到這一點,但這里是原始步驟。
映射:
PUT avgs/
{
"mappings": {
"properties": {
"values": {
"type": "nested",
"properties": {
"v1": {
"type": "integer"
},
"v2": {
"type": "integer"
}
}
}
}
}
}
索引:
POST avgs/_doc
{
"id": 1,
"name": "abc",
"score": 10,
"values": [
{
"v1": 1,
"v2": 2
}
]
}
POST avgs/_doc
{
"id": 2,
"name": "def",
"score": 20,
"values": [
{
"v1": 3,
"v2": 4
}
]
}
查詢:
GET avgs/_search
{
"size": 0,
"aggs": {
"avg_v1": {
"nested": {
"path": "values"
},
"aggs": {
"nested_v1": {
"avg": {
"field": "values.v1"
}
}
}
},
"avg_v2": {
"nested": {
"path": "values"
},
"aggs": {
"nested_v2": {
"avg": {
"field": "values.v2"
}
}
}
}
}
}
產量:
...
"aggregations" : {
"avg_v2" : {
"doc_count" : 2,
"nested_v2" : {
"value" : 3.0
}
},
"avg_v1" : {
"doc_count" : 2,
"nested_v1" : {
"value" : 2.0
}
}
}
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.