小编典典

ElasticSearch按文档字段分组并计数发生次数

elasticsearch

我的ElasticSearch 6.5.2索引看起来像:

      {
    "_index" : "searches",
    "_type" : "searches",
    "_id" : "cCYuHW4BvwH6Y3jL87ul",
    "_score" : 1.0,
    "_source" : {
      "querySearched" : "telecom",
    }
  },
  {
    "_index" : "searches",
    "_type" : "searches",
    "_id" : "cSYuHW4BvwH6Y3jL_Lvt",
    "_score" : 1.0,
    "_source" : {
      "querySearched" : "telecom",
    }
  },
  {
    "_index" : "searches",
    "_type" : "searches",
    "_id" : "eCb6O24BvwH6Y3jLP7tM",
    "_score" : 1.0,
    "_source" : {
      "querySearched" : "industry",
    }

我想要一个返回此结果的查询:

"result": 
{
"querySearched" : "telecom",
"number" : 2
},
{
"querySearched" : "industry",
"number" : 1
}

我只想按发生次数分组并获取每个事件的数量,最多只能有十个数字。我尝试使用聚合,但存储桶为空。谢谢!


阅读 536

收藏
2020-06-22

共1个答案

小编典典

案例映射

PUT /index
{
  "mappings": {
    "doc": {
      "properties": {
        "querySearched": {
          "type": "text",
          "fielddata": true
        }
      }
    }
  }
}

您的查询应如下所示

GET index/_search
{
  "size": 0,
  "aggs": {
    "result": {
      "terms": {
        "field": "querySearched",
        "size": 10
      }
    }
  }
}

您应该添加fielddata:true以启用聚集 文本
类型的字段更多的是

    "size": 10, => limit to 10

在与@Kamal简短讨论之后,我有义务告诉您,如果选择启用fielddata:true,则必须知道它会占用大量堆空间。

通过我分享的链接:

字段数据会占用大量堆空间,尤其是在加载高基数的文本字段时。一旦将字段数据加载到堆中,它在该段的生命周期内将一直保留在堆中。同样,加载字段数据是一个昂贵的过程,可能导致用户遇到延迟命中。这就是默认情况下禁用字段数据的原因。

另一种选择(更有效的选择):

PUT /index
{
  "mappings": {
    "doc": {
      "properties": {
        "querySearched": {
          "type": "text",
          "fields": {
           "keyword": {
             "type": "keyword",
             "ignore_above": 256
           }
         }
        }
      }
    }
  }
}

然后你的聚合查询

GET index/_search
{
  "size": 0,
  "aggs": {
    "result": {
      "terms": {
        "field": "querySearched.keyword",
        "size": 10
      }
    }
  }
}

两种解决方案都可以,但是您应该考虑这一点

希望能帮助到你

2020-06-22