弹性搜索多值字段聚合

时间:2015-06-08 13:53:08

标签: elasticsearch aggregation multivalue

我的索引文档有一个架构:

{
  ...
  'authors': [{'first name': 'John', 'last name': 'Smith'},
              {'first name': 'Mark', 'last name': 'Spencer'}]
  ...
}

我想搜索它们并由各个作者汇总,因此请在我的点击中找到顶级作者的列表。 some guides似乎与我的需求相匹配,但我无法让它在具有值列表的字段中工作。有什么帮助吗?

1 个答案:

答案 0 :(得分:1)

您可能希望使用nested type,然后可以在作者姓名上使用nested aggregation

举个例子,我设置了一个这样的简单索引:

PUT /test_index
{
   "settings": {
      "number_of_shards": 1
   },
   "mappings": {
      "doc": {
         "properties": {
            "title": {
               "type": "string"
            },
            "authors": {
               "type": "nested",
               "properties": {
                  "first_name": {
                     "type": "string"
                  },
                  "last_name": {
                     "type": "string"
                  }
               }
            }
         }
      }
   }
}

然后添加了几个文档:

PUT /test_index/doc/1
{
    "title": "Book 1",
   "authors": [
      {
         "first_name": "John",
         "last_name": "Smith"
      },
      {
         "first_name": "Mark",
         "last_name": "Spencer"
      }
   ]
}

PUT /test_index/doc/2
{
   "title": "Book 2",
   "authors": [
      {
         "first_name": "Ben",
         "last_name": "Jones"
      },
      {
         "first_name": "Tom",
         "last_name": "Lawrence"
      }
   ]
}

然后我可以通过以下方式获取(已分析)作者姓氏的列表:

POST /test_index/_search?search_type=count
{
   "aggs": {
      "nested_authors": {
         "nested": {
            "path": "authors"
         },
         "aggs": {
            "author_last_names": {
               "terms": {
                  "field": "authors.last_name"
               }
            }
         }
      }
   }
} 
...
{
   "took": 71,
   "timed_out": false,
   "_shards": {
      "total": 1,
      "successful": 1,
      "failed": 0
   },
   "hits": {
      "total": 2,
      "max_score": 0,
      "hits": []
   },
   "aggregations": {
      "nested_authors": {
         "doc_count": 4,
         "author_last_names": {
            "doc_count_error_upper_bound": 0,
            "sum_other_doc_count": 0,
            "buckets": [
               {
                  "key": "jones",
                  "doc_count": 1
               },
               {
                  "key": "lawrence",
                  "doc_count": 1
               },
               {
                  "key": "smith",
                  "doc_count": 1
               },
               {
                  "key": "spencer",
                  "doc_count": 1
               }
            ]
         }
      }
   }
}

以下是我使用的代码:

http://sense.qbox.io/gist/ca94cc11a12f8e4fed5c62c52966128b9a6f58de