ElasticSearch 无痛确定该字段是源文档中的数组

ElasticSearch painless determine that field was array in source document

Elasticsearch 包含类似

的文档
{
  "array":["1","2"],
  "str": "123"
}

有映射

"array" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          },
          "copy_to" : [
            "all"
          ],
          "norms" : false,
          "analyzer" : "logspeak"
        }

"str" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          },
          "copy_to" : [
            "all"
          ],
          "norms" : false,
          "analyzer" : "logspeak"
        }

如果我这样做

Debug.explain(doc['array.keyword']);

Debug.explain(doc['str.keyword']);

我得到了两个字段的 org.elasticsearch.index.fielddata.ScriptDocValues$Strings 类型。

如何确定源字段类型? (如果字段是简单字符串,我需要获取字符串长度;如果字段是数组,我需要获取数组大小)

正确的无痛表达是:

def size = -1;
if (doc['array.keyword'].size() > 0) {
    // string case
    if (doc['array.keyword'].size() == 1) {
        size = doc['array.keyword'].value.length();
    } 
    // array case
    else {
        size = doc['array.keyword'].values.size();
    }
}

正如official ES documentation of arrays中提到的,elasticsearch中没有数组数据类型,因为您使用的是字符串数组,ES解释API returns String。如果您想知道数组的大小,请参阅@Val 答案。