ElasticSearch - 仅搜索与搜索响应中所有顶级字段匹配的嵌套对象 [英] ElasticSearch - Get only matching nested objects with All Top level fields in search response

查看:114
本文介绍了ElasticSearch - 仅搜索与搜索响应中所有顶级字段匹配的嵌套对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我说下列文件:

{
    id: 1,
    name: "xyz",
    users: [{
        name: 'abc',
        surname: 'def'
    }, {
        name: 'xyz',
        surname: 'wef'
    }, {
        name: 'defg',
        surname: 'pqr'
    }]
}

我想在搜索响应中只获取匹配的所有顶级字段的嵌套对象。
我的意思是,如果我搜索/过滤名为abc的用户,我想要回应

I want to Get only matching nested objects with All Top level fields in search response. I mean If I search/filter for users with name 'abc', I want below response

{
    id: 1,
    name: "xyz",
    users: [{
        name: 'abc',
        surname: 'def'
    }]
}

我该怎么做?

参考:在弹性搜索中从数组中选择匹配对象

推荐答案

如果你拥有除了嵌套的所有根字段,然后只有嵌套字段中匹配的内部命中,那么我们可以通过指定一个稍微更多的源过滤参数重新使用以前的答案:

If you're ok with having all root fields except the nested one and then only the matching inner hits in the nested field, then we can re-use the previous answer like this by specifying a slightly more involved source filtering parameter:

{
  "_source": {
    "includes": [ "*" ],
    "excludes": [ "users" ]
  },
  "query": {
    "nested": {
      "path": "users",
      "inner_hits": {        <---- this is where the magic happens
        "_source": [
          "name", "surname"
        ]
      },
      "query": {
        "bool": {
          "must": [
            {
              "term": {
                "users.name": "abc"
              }
            }
          ]
        }
      }
    }
  }
}

这篇关于ElasticSearch - 仅搜索与搜索响应中所有顶级字段匹配的嵌套对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆