在弹性搜索中搜索文档内的匹配对象

Search matching object inside document in elasticsearch

我有一个文档,其中包含许多嵌套字段和对象数组。 那么当我执行搜索时,如何只获取对象数组中匹配的对象,而不是整个文档?

{
  "name": "Olivia",
  "jobs": [
    {
      "title": "Accountant",
      "offices": [
        {
          "city": "Paris",
          "address": "Her adress"
        },
        {
          "city": "NYC",
          "address": "New adress"
        }
      ]
    },
    {
      "title": "Judge",
      "offices": [
        {
          "city": "Paris",
          "address": "Judge adress"
        },
        {
          "city": "NYC",
          "address": "New judge adress"
        }
      ]
    }
  ]
}

工作和办公室是嵌套的 我想在搜索中找到的是:她的名字、工作和城市为“巴黎”的办公室,在正常搜索中,我得到城市为巴黎和纽约的两个办公室

有没有办法只获取以“巴黎”为城市的办公室?

您需要使用 nested inner_hits along with _source,只获取城市为“巴黎”的办公室

添加一个工作示例,其中包含索引数据(与问题中给出的相同)、映射、搜索查询和搜索结果

索引映射:

{
  "mappings": {
    "properties": {
      "jobs": {
        "type": "nested",
        "properties": {
          "offices": {
            "type": "nested"
          }
        }
      }
    }
  }
}

搜索查询:

{
  "query": {
    "nested": {
      "path": "jobs.offices",
      "query": {
        "bool": {
          "must": [
            {
              "match": {
                "jobs.offices.city": "Paris"
              }
            }
          ]
        }
      },
      "inner_hits": {
        "_source": [
          "jobs.offices.address"
        ]
      }
    }
  }
}

搜索结果:

 "inner_hits": {
          "jobs.offices": {
            "hits": {
              "total": {
                "value": 2,
                "relation": "eq"
              },
              "max_score": 0.6931471,
              "hits": [
                {
                  "_index": "67074755",
                  "_type": "_doc",
                  "_id": "1",
                  "_nested": {
                    "field": "jobs",
                    "offset": 0,
                    "_nested": {
                      "field": "offices",
                      "offset": 0
                    }
                  },
                  "_score": 0.6931471,
                  "_source": {
                    "address": "Her adress"
                  }
                },
                {
                  "_index": "67074755",
                  "_type": "_doc",
                  "_id": "1",
                  "_nested": {
                    "field": "jobs",
                    "offset": 1,
                    "_nested": {
                      "field": "offices",
                      "offset": 0
                    }
                  },
                  "_score": 0.6931471,
                  "_source": {
                    "address": "Judge adress"
                  }
                }
              ]
            }
          }
        }
      }