5

In my previous question, I was introduced to the fields in a query_string query and how it can help me to search nested fields of a document.

{
  "query": {
    "query_string": {
      "fields": ["*.id","id"],
      "query": "2"
    }
  }
}

But it only works for matching, what if I want to do some comparison? After some reading and testing, it seems queries like range do not support fields. Is there any way I can perform a range query, e.g. on a date, over a field that can be scattered anywhere in the document hierarchy?

i.e. considering the following document:

{
    "id" : 1,
    "Comment" : "Comment 1",
    "date" : "2016-08-16T15:22:36.967489",
    "Reply" : [ {
        "id" : 2,
        "Comment" : "Inner comment",
        "date" : "2016-08-16T16:22:36.967489"
    } ]
}

Is there a query searching over the date field (like date > '2016-08-16T16:00:00.000000') which matches the given document, because of the nested field, without explicitly giving the address to Reply.date? Something like this (I know the following query is incorrect):

{
    "query": {
        "range" : {
            "date" : {
                "gte" : "2016-08-16T16:00:00.000000",
            },
            "fields": ["date", "*.date"]
        }
    }
}
Community
  • 1
  • 1
Mehran
  • 15,593
  • 27
  • 122
  • 221

1 Answers1

3

The range query itself doesn't support it, however, you can leverage the query_string query (again) and the fact that you can wildcard fields and that it supports range queries in order to achieve what you need:

{
  "query": {
    "query_string": {
      "query": "\*date:[2016-08-16T16:00:00.000Z TO *]"
    }
  }
}

The above query will return your document because Reply.date matches *date

Val
  • 207,596
  • 13
  • 358
  • 360
  • Could you please explain / refer to a documentation on what the `\*` is doing? And should I be using `fields` as before? – Mehran Aug 17 '16 at 03:55
  • 2
    It's in the [query string query syntax](https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-query-string-query.html#_field_names) document in the "Field names" section. You don't need to use `fields` at all, the wildcard makes it unnecessary. `\*date` means any field ending with `date` (including nested ones). The backslash is there because we need to escape the wildcard `*` which is a reserved character in the query string syntax. – Val Aug 17 '16 at 03:58