Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Filter entries with a script condition

Using ElasticSearch 7.16.3, I want to define a filter to return all my products where value is superior to minimum + 30%

I have this query for now:

GET product_price/_search
{
  "query": {
    "bool": {
      "filter": {
        "script": {
          "script": """
            return doc['value'].value >= (doc['minimum'].value + (doc['minimum'].value * 30 / 100));
          """
        }
      }
    }
  }
}

And I get this error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

"reason" : "A document doesn’t have a value for a field! Use
doc[].size()==0 to check if a document is missing a field!"

My minimum field can be null, so of course I don’t want to apply filter on this. I tried to test the field, but since it’s a double, I can’t check if it’s null or not.

Is there a good way to do it?

>Solution :

You simply need to apply the formula only if both fields exist, like this:

GET product_price/_search
{
  "query": {
    "bool": {
      "filter": [
        {
          "exists": {
            "field": "value"
          }
        },
        {
          "exists": {
            "field": "minimum"
          }
        },
        {
          "script": {
            "script": """
                return doc['value'].value >= (doc['minimum'].value + (doc['minimum'].value * 30 / 100));
            """
          }
        }
      ]
    }
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading