ElasticSearch:获取嵌套字段

时间:2017-04-03 14:03:44

标签: json elasticsearch kibana

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

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

我希望我的查询结果成为名字" John"和#34; Alice"。 我尝试了几个聚合查询,例如:

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

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

1 个答案:

答案 0 :(得分:1)

您必须首先为您的索引声明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
          }
        }
      }
    }
  }
}

希望这有帮助

相关问题