Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make use of `gt` and `fields` in the same query in Elasticsearch

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"]
        }
    }
}
like image 200
Mehran Avatar asked Oct 18 '22 03:10

Mehran


1 Answers

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

like image 94
Val Avatar answered Oct 20 '22 23:10

Val