簡體   English   中英

在Elasticsearch中組合嵌套文檔中的缺失查詢和術語查詢

[英]Combining missing and term query in nested document in Elasticsearch

我有這3個文檔,其中fields的類型為nested

{
  "fields": [
    {"field_id": 23, "value": "John Doe"},
    {"field_id": 92, "value": null}
  ]
}

{
  "fields": [
    {"field_id": 23, "value": "Ada Lovelace"},
  ]
}

{
  "fields": [
    {"field_id": 23, "value": "Jack Daniels"},
    {"field_id": 92, "value": "jack@example.com"}
  ]
}

我需要在以下位置搜索文檔:

(`field_id` = `92` AND `value` is `null`) OR (`field_id` `92` is missing.)

組合術語和缺少查詢會導致僅返回具有null值的文檔:

...
"nested": {
  "path": "fields",
  "filter": {
    "bool": {
      "bool": {
        "must": [
          {
            "missing": {
              "field": "fields.value"
            }
          },
          {
            "terms": {
              "fields.field_id": [92]
            }
          }
        ]
      }
    }
  }
}
...

我怎樣才能做到這一點?

您已經有一個條件的查詢。 讓我們稱之為A。 對於第二種情況,請檢查嵌套文檔中的fields.field_id: 92 可以說這是B。 但是您的條件是fields.field_id: 92不應該存在。 因此要在must_not實現此環繞B。 B'

需要的是A B'

因此,最終查詢將是:

{
  "query": {
    "bool": {
      "should": [
        {
          "nested": {
            "path": "fields",
            "query": {
              "bool": {
                "must": [
                  {
                    "term": {
                      "fields.field_id": 92
                    }
                  }
                ],
                "must_not": [
                  {
                    "exists": {
                      "field": "fields.value"
                    }
                  }
                ]
              }
            }
          }
        },
        {
          "bool": {
            "must_not": [
              {
                "nested": {
                  "path": "fields",
                  "query": {
                    "term": {
                      "fields.field_id": 92
                    }
                  }
                }
              }
            ]
          }
        }
      ]
    }
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM