ElasticSearch:获取嵌套字段的所有值

问题描述:

我是ElasticSearch的新手,使用v5.1.2试图获取嵌套字段的所有值,在我的示例中为firstname中的值。我的数据:ElasticSearch:获取嵌套字段的所有值

PUT my_index/my_type/1 
{ 
    "group" : "fans", 
    "user" : [ 
    { 
     "firstname" : "John", 
     "lastname" : "Smith" 
    }, 
    { 
     "firstname" : "Alice", 
     "lastname" : "White" 
    }, 
    { 
     "lastname": "Muller" 
    } 
    ] 
} 

而且我想我的查询结果是第一个名字“约翰”和“爱丽丝”。 我尝试了几个聚合查询,例如:

GET my_index/my_type/_search 
{ 
    "size":0, 
    "aggs": { 
    "myagg": { 
     "terms": { 
     "field": "user.firstname" 
     } 
    } 
    } 
} 

但没有成功。我怎样才能做这种查询?

你必须首先声明与用户的指数mappings作为nested

PUT my_index3 
{ 
    "mappings": { 
    "my_type": { 
     "properties": { 
     "user": { 
      "type": "nested", 
      "properties": { 
      "firstname":{ 
       "type":"keyword" 
      } 
      } 
     } 
     } 
    } 
    } 
} 


PUT my_index3/my_type/1 
{ 
    "group" : "fans", 
    "user" : [ 
    { 
     "firstname" : "John", 
     "lastname" : "Smith" 
    }, 
    { 
     "firstname" : "Alice", 
     "lastname" : "White" 
    }, 
    { 
     "lastname": "Muller" 
    } 
    ] 
} 

声明映射你可以使用nested aggregations类似下面经过。

POST my_index3/_search 
{ 
    "size": 0, 
    "aggs": { 
    "nested_user": { 
     "nested": { 
     "path": "user" 
     }, 
     "aggs": { 
     "firstname": { 
      "terms": { 
      "field": "user.firstname", 
      "size": 10 
      } 
     } 
     } 
    } 
    } 
} 

希望这有助于

+0

这确实它,谢谢! – user1981275