Elasticsearch:如何搜索计算字段

时间:2016-01-25 05:10:41

标签: elasticsearch groovy

使用当前版本的Elasticsearch: The Definitive Guide中的数据,即:

[{
    "first_name" : "John",
    "last_name" :  "Smith",
    "age" :        25,
    "about" :      "I love to go rock climbing",
    "interests": [ "sports", "music" ]
}, {
    "first_name" :  "Jane",
    "last_name" :   "Smith",
    "age" :         32,
    "about" :       "I like to collect rock albums",
    "interests":  [ "music" ]
}, {
    "first_name" :  "Douglas",
    "last_name" :   "Fir",
    "age" :         35,
    "about":        "I like to build cabinets",
    "interests":  [ "forestry" ]
}]

我正在尝试使用请求数据运行一个简单的计算(我已经启用了Groovy脚本):

{
    "query": {
        "filtered": {
            "filter": {
                "range": {
                    "max_age": {
                        "gt": 150
                    }
                }
            }
        }
    },
    "script_fields": {
        "max_age": {
            "script": "_source.age * 5"
        }
    }
}

但ES没有返回任何数据。如何搜索计算字段?如果我不需要启用脚本,那就更好了。

1 个答案:

答案 0 :(得分:3)

script_fields在查询阶段后计算,即during the fetch phase,因此您无法在查询中引用脚本字段。

但是,您仍然可以使用script filter来完成您需要实现的目标,如下所示:

{
  "query": {
    "bool": {
      "must": {
        "script": {
          "script": {
            "inline": "doc['age'].value * factor > max_age",
            "params": {
              "factor": 5,
              "max_age": 150
            }
          }
        }
      }
    }
  }
}