gpt4 book ai didi

elasticsearch - 使用嵌套数组的最大值进行Elasticsearch中的总和聚合

转载 作者:行者123 更新时间:2023-12-02 22:19:31 25 4
gpt4 key购买 nike

我的索引中包含以下映射:

{
"testIndex": {
"mappings": {
"type1": {
"properties": {
"text": {
"type": "string"
},
"time_views": {
"type": "nested",
"properties": {
"timestamp": {
"type": "long"
},
"views": {
"type": "integer"
}
}
}
}
}
}
}
}

实际上,“time_views”是一个数组,但内部属性不是数组。此嵌套类型保存类型1的 View 计数的历史记录。 “ View ”是一个累积属性。

我想查询我的文档,以检索所有文档中“文本”字段中的任意单词出现在该文档中的“ View ”之和。

我知道我应该使用聚合,但我不知道如何进行此查询。
{
"query": {
"term":{
"text": "anyword"
}
},
"size": 0,
"aggs":{
???
}
}

正如我上面提到的,“time_views”是每个文档的数组,我只想使用每个数组的“views”的最大值。

Sample data


{
"text": "red car",
"time_views": [
{
"timestamp": 1651116565,
"views": 100
},
{
"timestamp": 1651546456,
"views": 153
},
{
"timestamp": 165446456,
"views": 200
}
]
},
{
"text": "blue car",
"time_views": [
{
"timestamp": 1651116565,
"views": 20
},
{
"timestamp": 1651546456,
"views": 70
},
{
"timestamp": 165446456,
"views": 130
}
]
},
{
"text": "green car",
"time_views": [
{
"timestamp": 1651116565,
"views": 4
},
{
"timestamp": 1651546456,
"views": 86
},
{
"timestamp": 165446456,
"views": 100
}
]
}

查询“汽车”时,我期望得到以下结果:
{
"text": "car"
"views": 430
}

其中430 = 200(第一文档的最大值)+ 130(第二文档的最大值)+ 100(第三文档的最大值)

我不在乎结果的Json结构,我只需要信息。

所以我该怎么做?
tnx :)

最佳答案

经过多次搜索,我终于找到了解决方案。我使用“scripted_metric”聚合并编写了一个自定义聚合。这是我的代码

{
"query": {
"term": {
"text": "car"
}
},
"aggs": {
"views_sum": {
"scripted_metric": {
"init_script": "_agg['maximum'] = []",
"map_script": "max = _source.time_views[0].views; for(tv in _source.time_views){ if(tv.views > max){max = tv.views; }}; _agg.maximum.add(max);",
"combine_script": "sum = 0; for (m in _agg.maximum) { sum += m }; return sum;",
"reduce_script": "sum = 0; for (a in _aggs) { sum += a }; return sum;"
}
}
},
"size": 0
}

这是我的结果:
{
"took": 3,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total": 3,
"max_score": 0,
"hits": []
},
"aggregations": {
"views_sum": {
"value": 430
}
}
}

关于elasticsearch - 使用嵌套数组的最大值进行Elasticsearch中的总和聚合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38484333/

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