Elasticsearch脚本查询数组字段大小比较

时间:2018-01-18 07:00:06

标签: elasticsearch

是否可以在Elasticsearch中对数组字段的长度进行比较?

例如以下作品(sourceId是文本类型字段)

GET /entity_active/_count
{
  "query": {
        "bool" : {
            "must" : {
                "script" : {
                    "script" : {
                        "inline": "doc['sourceId'].values.size() > 0",
                        "lang": "painless"
                     }
                }
            }
        }
    }
}

但以下不起作用(用户是数组字段)

GET /entity_active/_count
{
  "query": {
        "bool" : {
            "must" : {
                "script" : {
                    "script" : {
                        "inline": "doc['users'].values.size() > 0",
                        "lang": "painless"
                     }
                }
            }
        }
    }
}

后者返回这样的回复:

"error": {
    "root_cause": [
      {
        "type": "script_exception",
        "reason": "runtime error",
        "script_stack": [
 "org.elasticsearch.search.lookup.LeafDocLookup.get(LeafDocLookup.java:80)",
              "doc['users'].values.size() > 0",
          "    ^---- HERE"
        ],
        "script": "doc['users'].values.size() > 0",
        "lang": "painless"
      }
    ],
    "type": "search_phase_execution_exception",
    "reason": "all shards failed",
    "phase": "query",
    "grouped": true,

我是否需要使用其他方法来使用此类数组字段?

1 个答案:

答案 0 :(得分:0)

数组未在ES中编入索引,因此您无法通过doc_values访问数组(即通过doc.)。但是,您可以使用_source访问阵列所在的ctx._source文档。请尝试使用此脚本:

_source.users.size() > 0

_source.users.length > 0