无法创建嵌套日期聚合查询

时间:2019-04-11 08:46:00

标签: elasticsearch elasticsearch-aggregation

我正在尝试创建一个ElasticSearch聚合查询,该查询可以在所有摄取的文档中生成总和或均值。

文档的格式-

GET _search
{
"query": {
        "query_string": {
                "query": "cold"
                 }
        },
"size": 0,
"aggs": {
        "temperature": {
                    "date_histogram":{
                                      "field" : "date_1",
                                      "interval" : "month"
                                      },
                      "aggs":{
                              "temperature_agg":{
                                                "terms": {
                                                        "field": "feedback.value"
                                                          }
                                                }
                              }

                    }
        }
}

通过使用以下请求,我可以使用“ date_1”创建所有“ feedback.value”的总和-

{
 "mappings": {
  "catalog_item": {
   "properties": {

      "feedback":{
          "type":"nested",
          "properties":{
              "date_2":{
                  "type":   "date",
                  "format":"YYYY-MM-DD"
              }, 

                "value": {
                "type": "float"
              },

                "comment": {
                "type": "text"
              }


          }
        }

   }
  }
 }
}

但是,我需要基于“ feedback.date_2”对所有汇总的文档生成相同的查询。我不确定ElasticSearch是否可以解决这种聚合或如何进行聚合。任何指导都会有所帮助

[编辑] 映射文件(我仅定义嵌套项目,ES自己识别其他字段)

unitOfWork_stateUnderTest_expectedBehaviour

1 个答案:

答案 0 :(得分:1)

您需要使用nested documentssum aggregation

这是一个可行的示例:

样品映射:

PUT test
{
  "mappings": {
    "doc": {
      "properties": {
        "feedback": {
          "type": "nested"
        }
      }
    }
  }
}

添加示例文档:

PUT test/doc/1
{
   "date_1": "2017/08/07",
  "feedback": [
    {
      "date_2": "2017/08/07",
      "value": 28,
      "comment": "not cold"
    },
    {
      "date_2": "2017/08/09",
      "value": 48,
      "comment": "a bit chilly"
    },
    {
      "date_2": "2017/09/07",
      "value": 18,
      "comment": "very cold"
    }
  ]
}

基于date_2计算总和。

GET test/_search
{
  "size": 0,
  "aggs": {
    "temperature_aggregation": {
      "nested": {
        "path": "feedback"
      },
      "aggs": {
        "temperature": {
          "date_histogram": {
            "field": "feedback.date_2",
            "interval": "month"
          },
          "aggs": {
            "sum": {
              "sum": {
                "field": "feedback.value"
              }
            },
             "avg": {
              "avg": {
                "field": "feedback.value"
              }
            }
          }
        }
      }
    }
  }
}
相关问题