Elasticsearch 出生日期聚合

时间:2021-04-08 22:04:49

标签: elasticsearch

我需要我的过滤器像这样工作:

18-24 | (16,635,890)
25-34 | (2,478,382)
35-44 | (1,129,493)
45-54 | (5,689,393)
55-64 | (4,585.933)

这是我的 ES 映射:

{
  "dynamic": "strict",
  "properties": {
    "birthdate": {
      "type": "date",
      "format": "m/d/yyyy"
    },
    "first_name": {
      "type": "keyword"
    },
    "last_name": {
      "type": "keyword"
    }
  }
}

我想知道是否可以使用此映射执行此操作。我在 ES 方面不是很有经验,我相信要做到这一点,我需要在 ES 方面有高级知识。

另外,我尝试这样做来测试,但没有任何聚合:/

age: {
    terms: {
       field: 'birthdate'
    }
}

--------------------
"doc_count_error_upper_bound" => 0,
  "sum_other_doc_count" => 0,
    "buckets" => [
                 {
                               "key" => 1072915200000,
                     "key_as_string" => "0/1/2004",
                         "doc_count" => 1
                 }
             ]
         },

我尝试阅读文档并在某些论坛中搜索,但没有成功。谢谢

1 个答案:

答案 0 :(得分:0)

一个很好的候选者是 ranges aggregation 但由于您的 birthdate 被格式化为 date,您需要计算直到 now < em>之前你继续计算桶。您可以通过 Painless script 这样做。

综合起来:

POST your-index/_search
{
  "size": 0,
  "aggs": {
    "price_ranges": {
      "range": {
        "script": {
          "source": "return (params.now_ms - doc['birthdate'].value.millis) / 1000 / 60 / 60 / 24 / 365",
          "params": {
            "now_ms": 1617958584396
          }
        }, 
        "ranges": [
          {
            "from": 18,
            "to": 24,
            "key": "18-24"
          },
          {
            "from": 25,
            "to": 34,
            "key": "25-34"
          }
        ]
      }
    }
  }
}

会回来:

...
"aggregations" : {
  "price_ranges" : {
    "buckets" : [
      {
        "key" : "18-24",
        "from" : 18.0,
        "to" : 24.0,
        "doc_count" : 0
      },
      {
        "key" : "25-34",
        "from" : 25.0,
        "to" : 34.0,
        "doc_count" : 2
      }, 
      ...
    ]
  }
}

请注意,当前时间戳不是通过动态 new Date() 调用获得的,而是硬编码为参数化的 now_ms 变量。由于 Elasticsearch 的分布式特性,这是进行日期数学的推荐方法。有关这方面的更多信息,请查看 my answerHow to get current time as unix timestamp for script use


无耻插件:如果您对 ES 比较陌生,您可能会发现我最近发布的 Elasicsearch Handbook 很有用。其中一章专门介绍聚合,一章专门介绍无痛脚本!