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

查看:32
本文介绍了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'
        }
    ]
}

我该怎么做?

参考:在elasticsearch中从数组中选择匹配的对象

推荐答案

如果除了嵌套字段之外的所有根字段都可以,然后只有嵌套字段中匹配的内部命中,那么我们可以重新使用通过指定稍微复杂的源过滤参数,以前的答案是这样的:

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天全站免登陆