如何获取文本字段的 min/max 和平均长度?

How to get min/max and avg lengths of text field?

我有一个具有以下映射的索引:

        "properties": {
            "content": {
                "type":  "text",                
            },
            "ar_name": {
                "type": "text"
            }

        }

我想获取 content 的统计信息(最小长度、最大长度和平均长度) 场.

我该怎么做?

string_stats aggregation 提供该支持,但仅针对 keyword 字段。由于您的内容字段是 text 类型,我认为它包含 free-text 并不真正适合 keyword.

如果是这样,我建议您将 content 字段的长度存储在另一个整数字段(例如 content_length)中,然后您可以在 stats aggregation 中使用它那会 return 你期望的指标。

如果您想将字段保留为文本或者您不想更改映射,您可以通过聚合脚本来实现。这是一个示例查询:

{
  "size": 0,
  "aggs": {
    "min": {
      "min": {
        "script": {
          "source": """
            return doc['content'].value.length();
          """
        }
      }
    },
    "max": {
      "max": {
        "script": {
          "source": """
            return doc['content'].value.length();
          """
        }
      }
    },
    "avg": {
      "avg": {
        "script": {
          "source": """
            return doc['content'].value.length();
          """
        }
      }
    }
  }
}