0

假设我有一种查询语言,可以将“自然”语言查询解析为弹性搜索查询。

假设我们有以下查询:

(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"}
            }
        }
    }
}
4

1 回答 1

2

在 elasticsearch 中,您可以在bool 查询&&中认为asmust||as should ,因此您可以翻译此查询

(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"
            }
          }
        }
      ]
    }
  }
}

希望有帮助。

于 2019-09-27T11:45:49.630 回答