gpt4 book ai didi

数组项上的 Elasticsearch 聚合

转载 作者:行者123 更新时间:2023-12-04 05:37:21 28 4
gpt4 key购买 nike

下面给出的是我要在其上触发聚合查询的 Elasticsearch 文档。

{
"id": 1,
"attributes": [
{
"fieldId": 1,
"value": "Male"
},
{
"fieldId": 2,
"value": "12/11/2015"
}
]
}
{
"id": 2,
"attributes": [
{
"fieldId": 1,
"value": "Male"
},
{
"fieldId": 2,
"value": "11/11/2015"
}
]
}
结果必须如下。
[
{
"key": "Male",
"doc_count": 1
}
]
[
{
"key": "12/11/2015",
"doc_count": 1
},
{
"key": "11/11/2015",
"doc_count": 1
}
]
有没有办法在 Elasticsearch 中实现这一点?

最佳答案

这是可能的。看这个例子:

我们必须将属性映射为 nested类型以便能够正确聚合。

PUT /test
{
"mappings": {
"sample": {
"properties": {
"id": {
"type": "integer"
},
"attributes": {
"type": "nested",
"properties": {
"fieldId": {
"type": "integer"
},
"value": {
"type": "string",
"index": "not_analyzed"
}
}
}
}
}
}
}

让我们添加您给定的测试数据:

PUT /test/sample/1
{"id":1,"attributes":[{"fieldId":1,"value":"Male"},{"fieldId":2,"value":"12/11/2015"}]}
PUT /test/sample/2
{"id":2,"attributes":[{"fieldId":1,"value":"Male"},{"fieldId":2,"value":"11/11/2015"}]}

最后让我们运行这个查询:

GET /test/_search
{
"size": 0,
"query": {
"match_all": {}
},
"aggs": {
"Nest": {
"nested": {
"path": "attributes"
},
"aggs": {
"fieldIds": {
"terms": {
"field": "attributes.fieldId",
"size": 0
},
"aggs": {
"values": {
"terms": {
"field": "attributes.value",
"size": 0
}
}
}
}
}
}
}
}

它会做什么?
  • 运行 nested先聚合才能进入nested对象并正确聚合它们。
  • 使用 terms 创建存储桶每个 fieldId 的聚合,在您的情况下,我们将获得其中两个:12 .
  • 运行 terms再次对上面的每个存储桶进行聚合以获得相应的值。

  • 这就是输出。

    {
    "took": 2,
    "timed_out": false,
    "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
    },
    "hits": {
    "total": 2,
    "max_score": 0,
    "hits": []
    },
    "aggregations": {
    "Nest": {
    "doc_count": 4,
    "fieldIds": {
    "doc_count_error_upper_bound": 0,
    "sum_other_doc_count": 0,
    "buckets": [
    {
    "key": 1,
    "doc_count": 2,
    "values": {
    "doc_count_error_upper_bound": 0,
    "sum_other_doc_count": 0,
    "buckets": [
    {
    "key": "Male",
    "doc_count": 2
    }
    ]
    }
    },
    {
    "key": 2,
    "doc_count": 2,
    "values": {
    "doc_count_error_upper_bound": 0,
    "sum_other_doc_count": 0,
    "buckets": [
    {
    "key": "11/11/2015",
    "doc_count": 1
    },
    {
    "key": "12/11/2015",
    "doc_count": 1
    }
    ]
    }
    }
    ]
    }
    }
    }
    }

    这不是你所要求的。但这与您在 Elasticsearch 中所能获得的最接近。

    关于数组项上的 Elasticsearch 聚合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34826804/

    28 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com