如何使用 ELK 堆栈中的 elasticsearch 查询获取数组的长度?

How do I get the length of an array using an elasticsearch query in the ELK stack?

我正在使用 Kibana 并且有一个如下所示的索引

GET index_name/

{
  "index_name": {
    "aliases": {},
    "mappings": {
      "json": {
        "properties": {
          "scores": {
            "type": "text",
            "fields": {
              "keyword": {
                "type": "keyword",
                "ignore_above": 256
              }
            }
          }
        }
      }
    }

我想获取每个记录的scores数组的长度(即其中有多少text个元素),最终目标是过滤掉长度为大于或等于 20。到目前为止,我能够识别(突出显示)每条记录为“20”但似乎无法构建一个过滤器,然后我可以将其转换为布尔值(1 true) 供以后使用/汇总满足条件的记录。单击 'Edit Query DSL':

后,我将其放入发现面板的过滤器中
{
  "query": {
    "match": {
      "scores": {
        "query": "20",
        "type": "phrase"
      }
    }
  }
}

编辑:文档中此字段的示例是:

scores:12, 12, 12, 20, 20, 20

在 table 选项卡视图中,它旁边有一个 t,表示 text。该字段的长度因记录而异,从 1 项到 20 多项不等。我也不知道如何通过查询返回给我的这个字段的长度(仅),但我看到了一些其他的答案,这些答案暗示了这样的事情(这对我来说会产生错误):

"filter" : {
    "script" : {
        "script" : "doc['score'].values.length > 10"
    }
}

有几个选项

这是查找任意大小的项目数量的地方(通过,分隔)。

{
  "query": {
    "bool": {
      "filter": {
        "script": {
          "script": {
            "source":"/, /.split(doc['score.keyword'].value).length > 20"
          }
        }
      }
    }
  }
}

注意:对于上述解决方案,需要在 elasticsearch.yml 中设置 script.painless.regex.enabled: true

如果所有分数都具有特定大小(即全部只有两位数),则字符串长度(如您所尝试的那样)将起作用:

{
  "query": {
    "bool": {
      "filter": {
        "script": {
          "script": {
            "source":"doc['scores.keyword'].value.length() > 78"
          }
        }
      }
    }
  }
}

我选78是因为每一项(假设2位数)是2位数+,==4,你要看大于20的,就是19 * 4 + 2

如果您经常关心这个分数数组的大小,您可能应该这样存储它。您可以使用 split processor 在摄取管道中进行处理以实现此目的。