使用elastisearch的邮件域的聚合计数

时间:2018-05-30 07:07:07

标签: regex elasticsearch aggregation

我的索引中有以下文档:

{
    "name":"rakesh"
    "age":"26"
    "email":"rakesh@gmail.com"
}

{
    "name":"sam"
    "age":"24"
    "email":"samjoe@elastic.com"
}

{
    "name":"joseph"
    "age":"26"
    "email":"joseph@gmail.com"
}

{
    "name":"genny"
    "age":"24"
    "email":"genny@hotmail.com"
}

现在我需要获取所有邮件域的数量。像:

@gmail.com:2,
@hotmail.com:1,
@elastic.com:1

使用弹性搜索聚合。

我能够找到与给定查询匹配的记录。但我需要计算每个域名。

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

这可以通过创建仅包含电子邮件域名的子字段轻松实现。首先使用适当的分析器创建索引:

PUT my_index
{
  "settings": {
    "index": {
      "analysis": {
        "analyzer": {
          "email_domain_analyzer": {
            "type": "pattern",
            "pattern": "(.+)@",
            "lowercase": true
          }
        }
      }
    }
  },
  "mappings": {
    "doc": {
      "properties": {
        "email": {
          "type": "text",
          "fields": {
            "domain": {
              "type": "text",
              "fielddata": true,
              "analyzer": "email_domain_analyzer"
            }
          }
        }
      }
    }
  }
}

然后创建您的文档:

POST my_index/doc/_bulk
{ "index": {"_id": 1 }}
{ "name":"rakesh", "age":"26", "email":"rakesh@gmail.com" }
{ "index": {"_id": 2 }}
{ "name":"sam", "age":"24", "email":"samjoe@elastic.com" }
{ "index": {"_id": 3 }}
{ "name":"joseph", "age":"26", "email":"joseph@gmail.com" }
{ "index": {"_id": 4 }}
{ "name":"genny", "age":"24", "email":"genny@gmail.com" }

最后,您可以在email.domain字段进行汇总,然后您就能获得所需内容:

POST my_index/_search
{
  "size": 0,
  "aggs": {
    "domains": {
      "terms": {
        "field": "email.domain"
      }
    }
  }
}