How can I perform math operations on fields in elasticsearch while searching?

Viewed 1807

Is there any way to perform in Elasticsearch math operations like one described below in SQL? If yes, what is the best way to perform such search operation?

select * from products where price + 50 > 20
1 Answers

This is feasible using a painless script query (https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-script-query.html).

Just give this a try:

GET /products/_search
{
    "query": {
        "bool" : {
            "must" : {
                "script" : {
                    "script" : {
                        "source": "(doc['price'].value + 50) > 20",
                        "lang": "painless"
                    }
                }
            }
        }
    }
}

A prepared statement like behaviour can be done like this:

GET /products/_search
{
    "query": {
        "bool" : {
            "must" : {
                "script" : {
                    "script" : {
                        "source": "(doc['price'].value + params.foo) > params.bar",
                        "lang": "painless",
                        "params" : {
                            "foo" : 50,
                            "bar" : 20
                        }
                    }
                }
            }
        }
    }
}
Related