gpt4 book ai didi

elasticsearch - 如何在ElasticSearch中搜索和分组?

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

我有记录像这样的ElasticSearch索引:

{
"project" : "A",
"updated" : <date>,
"cost" : 123
},
{
"project" : "A",
"updated" : <date>,
"cost" : 1
},
{
"project" : "B",
"updated" : <date>,
"cost" : 3
},
{
"project" : "B",
"updated" : <date>,
"cost" : 4
},
{
"project" : "C",
"updated" : <date>,
"cost" : 5
}

我正在尝试按选定的项目绘制“成本”图表。
谁能帮助我建立查询以获取成本总和,按项目分组的数据?
F.e.我想为项目“A”和“B”选择数据,并得到类似以下内容:
date1 ->
projectA -> sum(cost)
projectB -> sum(cost)
date2 ->
projectA -> sum(cost)
projectB -> sum(cost)

不知道如何修改此查询,该查询将提取一个项目的数据:
    "query": {
"bool": {
"must": [
{
"match": {
"project": {
"query": <project>,
"type": "phrase"
}
}
},
{
"range": {
"updated": {
"gte": <startDate>,
"format": "epoch_millis"
}
}
}
]
}
},
"aggs": {
"3": {
"date_histogram": {
"field": "End_Time",
"interval": "1M",
"time_zone": "CST6CDT",
"min_doc_count": 1
},
"aggs": {
"2": {
"sum": {
"field": "cost"
}
}
}
}
}

Upd: Thanks guys! With your help I wrote the query:


{
"query": {
"bool": {
"must": [
{
"range": {
"End_Time": {
"gte": 1485892800000,
"format": "epoch_millis"
}
}
}
],
"should": [
{
"match": {
"Project_Name": {
"query": "A",
"type": "phrase"
}
}
},
{
"match": {
"Project_Name": {
"query": "B",
"type": "phrase"
}
}
}
]
}
},
"aggs": {
"3": {
"date_histogram": {
"field": "End_Time",
"interval": "1M",
"time_zone": "CST6CDT",
"min_doc_count": 1
},
"aggs": {
"project_agg": {
"terms": {
"field": "Project_ID"
},
"aggs": {
"2": {
"sum": {
"field": "Cost"
}
}
}
}
}
}
}
}

但是它返回一些奇怪的东西:
"aggregations": {
"3": {
"buckets": [
{
"key_as_string": "2017-02-01T00:00:00.000-06:00",
"key": 1485928800000,
"doc_count": 17095,
"project_agg": {
"doc_count_error_upper_bound": 36,
"sum_other_doc_count": 3503,
"buckets": [
{
"2": {
"value": 2536.8616891294323
},
"key": 834879987748,
"doc_count": 2243
},
{
"2": {
"value": 3438.766646153458
},
"key": 497952557271,
"doc_count": 1785
},
{
"2": {
"value": 13066.367076588496
},
"key": 1057394416300,
"doc_count": 1736
},
...

每个月有10个水桶。我希望每个项目只能看到2个值。怎么了?

最佳答案

您编写的查询提供了每月的总费用(与项目无关),您需要在aggregation 3aggregation 2之间进行另一项汇总,以便按项目分组。

如果只需要AB项目,则在聚合中使用过滤器。

"size": 0,
"aggs": {
"project": {
"filter": {
"bool": {
"must": [
{
"terms": {
"project": [
"a",
"b"
]
}
}
]
}
},
"aggs": {
"3": {
"date_histogram": {
"field": "End_Time",
"interval": "1M",
"time_zone": "CST6CDT",
"min_doc_count": 1
},
"aggs": {
"project_agg": {
"terms": {
"field": "project"
},
"aggs": {
"2": {
"sum": {
"field": "cost"
}
}
}
}
}
}
}
}
}

关于elasticsearch - 如何在ElasticSearch中搜索和分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45755660/

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