Nested解决Object数组问题

如果你想要使用对象数组格式,同时又想保持数组中每个Object的独立性。那么你应该使用nested类型。nested类型会把数组中的每个object用隐式的独立Document来保存,因此可以互不干扰的查询,但必须用nested方式查询。

首先,我们设置一个nested类型的字段:引入nested字段的类型

PUT my_index
{
  "mappings": {
    "properties": {
      "user": {
        "type": "nested",
        "properties": {
          "first":{"type":"keyword"},
          "last":{"type":"keyword"}
        }
      }
    }
  }
}

然后,再次填充数据:

PUT my_index/_doc/1
{
  "group" : "fans",
  "user" : [
    {
      "first" : "John",
      "last" :  "Smith"
    },
    {
      "first" : "Alice",
      "last" :  "White"
    }
  ]
}

搜索的时候,必须使用nested搜索,并制定对象的名称:

GET my_index/_search
{
  "query": {
    "nested": {
      "path": "user",
      "query": {
        "bool": {
          "must": [
            { "match": {"user.first": "Alice"} },
            { "match": { "user.last": "White"} }
          ]
        }
      }
    }
  }
}

语法说明:
在这里插入图片描述
这次就搜索不到数据了,因为没有名为Alice Smith的人。

{
  "took" : 0,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 0,
      "relation" : "eq"
    },
    "max_score" : null,
    "hits" : [ ]
  }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值