如何使用elasticsearch在12个月后对嵌套对象进行过滤和聚合?

sd2nnvve  于 2021-06-10  发布在  ElasticSearch
关注(0)|答案(1)|浏览(647)

我有一份下列文件:

{
    "id": {"type": "integer"},
    "owner": {"type": "object"},
    "company_id": {"type": "integer"},
    "summary": {"type": "object"},
    "create_date": {"type": "date"},
}

所以基本上我想过滤所有者的id和12个月后基于创建日期。然后对摘要对象中的键执行聚合。
我拥有的数据示例:

id     |   owner                   | company_id    | summary                              | create_date
01     |   {"id": 1, "name": "x"}  | 1             | {"data1": 2, "data2": 5, "data3": 6} | "2020-09-22T01:04:17.852112Z"
02     |   {"id": 2, "name": "y"}  | 2             | {"data1": 2, "data2": 5, "data4": 6} | "2020-09-17T04:11:45.851231Z"
03     |   {"id": 3, "name": "z"}  | 3             | {"data1": 0, "data2": 4, "data3": 6} | "2019-02-02T12:19:27.852121Z"

我想要的数据。

month-year                                       | aggregate of summary keys
09-2020 (any indicator/format of month and year) |{"data1":1, "data2": 5, "data3": 6, "data4": 6}

这里的数据,我想平均内的所有键摘要对象根据每个月的过去12个月。

50pmv0ei

50pmv0ei1#

GET data/_search
{
  "size": 0, // <====== Represent that query o/p is not required, only aggs
  "query": {
    "bool": {
      "filter": [
        {
          "range": {
            "create_date": {
              "gte": "now-6M" // <========== 'M' represent month, now represents current timestamp
            }
          }
        },
        {
          "term": {
            "owner.id": 4
          }
        }
      ]
    }
  },
  "aggs": {
    "NAME": {   //<====== Custom name you can provide to this aggregation
      "terms": {    // <============ You need grouping based on the field and count of the grouped field will be returned
        "field": "summary.v1",
        "size": 10 // <==== How many data points needs to be returned
      }
    }
  }
}

查询中添加了一些详细信息。其他需要学习的重要事项:
查询和筛选器
术语聚合
编辑:如果您需要每月平均值,请在现有查询中使用下面的聚合部分。

"aggs": {
"monthly_grouping": {
 "date_histogram": {
   "field": "create_date",
   "interval": "month",
   "missing": "0"
 },"aggs": {
    "average_V1": {
      "avg": {
        "field": "summary.v1"
      }
    },
    "average_V2": { //<===== Similarly add other fields if required
      "avg": {
        "field": "summary.v1"
      }
    }
  }
}
}

在这里阅读日期直方图。

相关问题