Elasticsearch聚合:始终在术语聚合中返回一个字段

时间:2016-09-05 06:26:43

标签: elasticsearch

我的所有用户都有一个与之关联的城市,我正在对其进行汇总。我总是希望从聚合响应返回Unspecified字段以获取尚未进入其城市的用户。有没有办法让我总能得到Unspecified的结果,无论其数量是否在前10名。由于城市的数量非常大,我不想查询所有城市只是为了获得Unspecified的数量。

数据架构是:

"mappings": {
     "users": {
        "dynamic": "false",
        "_all": {
           "enabled": false
        },
        "properties": {
           "city": {
              "properties": {
                 "geopoint": {
                    "type": "geo_point"
                 },
                 "name": {
                    "type": "string",
                    "index": "not_analyzed"
                 }
              }
           },
           "id": {
              "type": "integer"
           }
       ...}

我正在做的聚合是:

{
  "aggs" : {
    "cities" : {
        "terms" : { "field" : "city.name" }
    }
  }
}

我还有其他一些查询和过滤器。这种聚合工作正常。我得到了十大城市的名单,但我也是Unspecified

的统计数字

预期结果是:

"aggregations" : {
    "cities" : {
        "buckets" : [ 
            {
                "key" : "New York",
                "doc_count" : 120
            },
            {
                "key" : "Chicago",
                "doc_count" : 50
            },
             .
             .
             .
            {
                "key" : "Unspecified",
                "doc_count" : 4
            },
        ]
    }
}

1 个答案:

答案 0 :(得分:0)

您可以利用terms聚合的missing value设置。您只需指定存储桶的密钥,该密钥将收集在指定字段中没有任何字词的所有文档:

{
  "aggs" : {
    "cities" : {
        "terms" : { 
           "field" : "city.name",
           "missing": "Unspecified"                 <--- add this
        }
    }
  }
}