1

Let's say I have a query language that parses "natural" language queries into elastic search queries.

Assuming we have the following query:

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

How can I achieve this in elastic search?

I've tried with:

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

but this is not what I want.

What am I doing wrong?

Mapping:

{
    "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"}
            }
        }
    }
}
Patryk
  • 22,602
  • 44
  • 128
  • 244

1 Answers1

5

In elasticsearch you can think of && as must and || as should in bool query, so you can translate this query

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

as

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

which gives us this query when we want to convert it to elasticsearch DSL

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

Hope that helps.

Rob
  • 9,664
  • 3
  • 41
  • 43
  • Can I aggregate `term` entries under `should` so instead of having an array under `should` with objects containing `"term"` I'd have a `"term"` entry with an array of key value pairs? – Patryk Sep 27 '19 at 11:53
  • You can only use term query to search for value/values on one field, you can't pass multiple fields, so I think you won't be able to do this. – Rob Sep 27 '19 at 11:57