首页 > 解决方案 > 从elasticsearch中的关键类别获取数据

问题描述

我有这些文件:

curl -XPOST -H 'Content-Type: application/json' "http://localhost:9200/test/_bulk?pretty" -d'
{"index":{"_index":"test","_type":"product"}}
{"id_product":"1", "categories":[1,2] }
{"index":{"_index":"test","_type":"product"}}
{"id_product":"2", "categories":[25,28] }

我只需要获取类别。我能得到类似的输出吗?

[1,2,25,28]

标签: elasticsearch

解决方案


我认为没有办法告诉 ES 返回 only categories,但您可以使用术语聚合来提取搜索上下文具有的所有类别。

例子:

{
  "size":0,
  "aggs":{
    "byCategory":{
      "terms":{
        "field": "categories"
      }
    }
  }
}

这将返回如下内容:

{
  "aggregations": {
    "byCategory": {
      "doc_count_error_upper_bound": 0,
      "sum_other_doc_count": 0,
      "buckets": [
        {
          "key": 1,
          "doc_count": 1
        },
        {
          "key": 2,
          "doc_count": 1
        },
        {
          "key": 25,
          "doc_count": 1
        },
        {
          "key": 28,
          "doc_count": 1
        }
      ]
    }
  }
}

如您所见,现在您可以遍历buckets.key以提取搜索中存在的所有类别。


推荐阅读