如何从多个术语查询中匹配一个?

How to match one from many terms query?

假设我有一种查询语言,可以将 "natural" 语言查询解析为弹性搜索查询。

假设我们有以下查询:

(type == "my-type" || device_id == "some-device-id") && id == "123456789"

如何在弹性搜索中实现这一点?

我试过:

{
    "bool": {
        "filter": {
            "term": {
                "id": "123456789"
            }
        },
        "should": [
            {
                "term": {
                    "type": "my-type"
                }
            },
            {
                "term": {
                    "device_id": "some-device-id"
                }
            }
        ]
    }
}

但这不是我想要的。

我做错了什么?

映射:

{
    "mappings": {
        "_doc": {
            "properties": {
                "accepted_at":  {
                    "type": "date",
                    "format": "strict_date_optional_time||date_time||epoch_millis"
                },
                "created_at":   {
                    "type": "date",
                    "format": "strict_date_optional_time||date_time||epoch_millis"
                },
                "device_id":    {"type": "keyword"},
                "id":       {"type": "keyword"},
                "location": {"type": "geo_point"},
                "message_id":   {"type": "keyword"},
                "type":     {"type": "keyword"}
            }
        }
    }
}

在 elasticsearch 中,您可以将 && 视为 must,将 || 视为 bool query,因此您可以翻译此查询

(type == "my-type" || device_id == "some-device-id") && id == "123456789"

作为

must(should(type == "my-type"),(device_id == "some-device-id"), id == "123456789")

当我们想将其转换为 elasticsearch DSL 时,它会为我们提供此查询

{
  "query": {
    "bool": {
      "must": [
        {
          "bool": {
            "should": [
              {
                "term": {
                  "type": {
                    "value": "my-type"
                  }
                }
              },
              {
                "term": {
                  "device_id": {
                    "value": "some-device-id"
                  }
                }
              }
            ]
          }
        },
        {
          "term": {
            "id": {
              "value": "123456789"
            }
          }
        }
      ]
    }
  }
}

希望对您有所帮助。