在Elasticsearch中组合嵌套文档中的缺失查询和术语查询

时间:2019-01-02 15:54:30

标签: 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]
            }
          }
        ]
      }
    }
  }
}
...

我该怎么做?

1 个答案:

答案 0 :(得分:0)

您已经查询了一个条件。我们称之为 A 。对于第二种情况,请检查嵌套文档中的fields.field_id: 92。可以说这是 B 。但是您的条件是fields.field_id: 92不应该存在。因此,要在must_not中实现 B 换行。即 B'

所需的是 A OR 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
                    }
                  }
                }
              }
            ]
          }
        }
      ]
    }
  }
}