小编典典

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

elasticsearch

假设我有以下文档:

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

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

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

我怎样才能做到这一点?


阅读 402

收藏
2020-06-22

共1个答案

小编典典

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

{
  "_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"
              }
            }
          ]
        }
      }
    }
  }
}
2020-06-22