首页 > 解决方案 > 如何在搜索时对弹性搜索中的字段执行数学运算?

问题描述

有没有什么方法可以在 Elasticsearch 数学运算中执行,就像下面在 SQL 中描述的那样?如果是,执行此类搜索操作的最佳方法是什么?

select * from products where price + 50 > 20

标签: elasticsearchmathsearch

解决方案


使用无痛脚本查询(https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-script-query.html)是可行的。

试试这个:

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

类似行为的准备好的语句可以这样完成:

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

推荐阅读