Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arithmetic operations with fields

Is it possible to query the result of a subtraction between two fields?

E.g. There are two fields: "start", "end". I would like documents with end - start > 10.

Can this be done directly or the only way to do is to create a new field while loading the documents with this difference?

like image 485
Diolor Avatar asked Jan 10 '23 12:01

Diolor


1 Answers

You can use script filters using the scripting syntax explained in the scripting documentation.

For your specific issue, you might do something like

{
  "query": {
    "filtered": {
      "query": {
        "match_all": {}
      },
      "filter": {
        "script": {
          "script": "doc['end'].value - doc['start'].value > 10"
        }
      }
    }
  }
}

where you can replace the match_all query with your own.

As it's probably clear from the code above, you can access specific fields in your document with the sintax doc['field'] and apply specific functions to their values. In this case, .value (without parenthesis) returns the value of the field itself.

like image 185
Michele Palmia Avatar answered Mar 28 '23 09:03

Michele Palmia