首页 > 解决方案 > Elasticsearch - 按字段获取结果摘要

问题描述

{"name": "John", "district": 1, "light": 2},
{"name": "John", "district": 5, "light": 2},
{"name": "John", "district": 5, "light": 27},
{"name": "John", "district": 11, "light": 1},
{"name": "John", "district": 11, "light": 0},
{"name": "John", "district": 11, "light": 10},
{"name": "John", "district": 8, "light": 6},
{"name": "Mary", "district": 2, "light": 10},
{"name": "Nick", "district": 1, "light": 0},
{"name": "Bob", "district": 3, "light": 10},
{"name": "Kenny", "district": 1, "light": 8}

按名称字段搜索时,如何按组数获取剩余字段的摘要?

例子:

搜索时

  "query": {
    "term": {
      "name": {
        "value": "john"
      }
    }
  }

预期输出:

{
  "district": {
    11: 3, // value : the amount of matches
    5: 2,
    1: 1,
  },
  "light": {
    2: 2, // value : the amount of matches
    27: 1,
    10: 1,
    // etc..
  }
}

标签: phpelasticsearchaggregate

解决方案


尝试一对术语聚合:

{
  "size": 0, 
  "query": {
    "term": {
      "name": {
        "value": "john"
      }
    }
  },
  "aggs": {
    "by_district": {
      "terms": {
        "field": "district"
      }
    },
    "by_light": {
      "terms": {
        "field": "light"
      }
    }
  }
}

推荐阅读