在Elasticsearch中查询具有嵌套对象的数组以获取多个对象

s8vozzvw  于 2022-11-02  发布在  ElasticSearch
关注(0)|答案(1)|浏览(167)

我在Elasticsearch中有以下格式的数据-

"segments": [
  {"id": "ABC", "value":123},
  {"id": "PQR", "value":345},
  {"id": "DEF", "value":567},
  {"id": "XYZ", "value":789},
]

我想检索ID为“ABC”或“DEF”的所有段。
我在YouTube上查找了文档(https://www.elastic.co/guide/en/elasticsearch/reference/7.9/query-dsl-nested-query.html)和一些示例,但所有的都看起来只检索一个对象,而我想检索多个对象。
有办法做到这一点吗?

xeufq47z

xeufq47z1#

您可以使用具有内部命中嵌套查询,如here所示
我希望您索引Map如下所示,并且segments字段定义为nested

"mappings": {
      "properties": {
        "segments": {
          "type": "nested",
          "properties": {
            "id": {
              "type": "text",
              "fields": {
                "keyword": {
                  "type": "keyword",
                  "ignore_above": 256
                }
              }
            },
            "value": {
              "type": "long"
            }
          }
        }
      }
    }

您可以使用以下查询

{
  "_source" : false,
  "query": {
    "nested": {
      "path": "segments",
      "query": {
        "terms": {
          "segments.id.keyword": [
            "ABC",
            "DEF"
          ]
        }
      },
      "inner_hits": {}
    }
  }
}

回应:

"hits": {
    "total": {
      "value": 1,
      "relation": "eq"
    },
    "max_score": 1,
    "hits": [
      {
        "_index": "73895503",
        "_id": "TmM8iYMBrWOLJcwdvQGG",
        "_score": 1,
        "inner_hits": {
          "segments": {
            "hits": {
              "total": {
                "value": 2,
                "relation": "eq"
              },
              "max_score": 1,
              "hits": [
                {
                  "_index": "73895503",
                  "_id": "TmM8iYMBrWOLJcwdvQGG",
                  "_nested": {
                    "field": "segments",
                    "offset": 0
                  },
                  "_score": 1,
                  "_source": {
                    "id": "ABC",
                    "value": 123
                  }
                },
                {
                  "_index": "73895503",
                  "_id": "TmM8iYMBrWOLJcwdvQGG",
                  "_nested": {
                    "field": "segments",
                    "offset": 2
                  },
                  "_score": 1,
                  "_source": {
                    "id": "DEF",
                    "value": 567
                  }
                }
              ]
            }
          }
        }
      }
    ]
  }

相关问题