ElasticSearch - 仅搜索与搜索响应中的所有顶级字段匹配的嵌套对象

Jay*_*hah 14 elasticsearch

让我说我有以下文件:

{
    id: 1,
    name: "xyz",
    users: [
        {
            name: 'abc',
            surname: 'def'
        },
        {
            name: 'xyz',
            surname: 'wef'
        },
        {
            name: 'defg',
            surname: 'pqr'
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

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

{
    id: 1,
    name: "xyz",
    users: [
        {
            name: 'abc',
            surname: 'def'
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

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

Val*_*Val 18

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

{
  "_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"
              }
            }
          ]
        }
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 顺便说一句,我们可以通过将 inner_hits 保持为空来获取嵌套对象的所有字段,即 "inner_hits": { } (3认同)