我正在基于Elasticsearch构建分层导航。我的产品具有“品牌”字段。例如,我有2个品牌-Tommy Jeans和Tommy Hilfiger。当我尝试使用以下查询汇总结果时

$params = [
    'index' => 'my_index',
    'type' => 'my_type',
    'body' => [
        'query' => [
            'term'  => [
                'brand' => 'tommy'
            ]
        ],
        'aggs' => [
            'brand' => [
                'terms' => [
                    'field' => 'brand',
                ]
            ]
        ]
    ]
];

我期望括号中有2个结果-Tommy Hilfiger和Tommy Jeans都有结果计数,但就我而言,它是这样的
[aggregations] => Array
    (
        [brand] => Array
            (
                [doc_count_error_upper_bound] => 0
                [sum_other_doc_count] => 0
                [buckets] => Array
                    (
                        [0] => Array
                            (
                                [key] => tommy
                                [doc_count] => 6
                            )

                        [1] => Array
                            (
                                [key] => hilfiger
                                [doc_count] => 4
                            )

                        [2] => Array
                            (
                                [key] => jeans
                                [doc_count] => 2
                            )

                    )

            )

    )

我该如何解决?

最佳答案

这可以通过使类型为brandtext字段并向其添加一个子字段为keyword和类型为keyword来实现。然后,您需要在字段term上使用brand查询来过滤结果并在字段brand.keyword上进行汇总

因此,映射将为:

{
  "mappings": {
    "_doc": {
      "properties": {
        "brand": {
          "type": "text",
          "fields": {
            "keyword": {
              "type": "keyword"
            }
          }
        }
      }
    }
  }
}

更新注释:映射旧版本的es(2.x):
{
  "mappings": {
    "_doc": {
      "properties": {
        "brand": {
          "type": "string",
          "fields": {
            "keyword": {
              "type": "string",
              "index": "not_analyzed"
            }
          }
        }
      }
    }
  }
}

以下是查询:
{
  "query": {
    "bool": {
      "filter": [
        {
          "term": {
            "brand": "tommy"
          }
        }
      ]
    }
  },
  "aggs": {
    "brand": {
      "terms": {
        "field": "brand.keyword"
      }
    }
  }
}

07-24 09:39