首页 > 解决方案 > 如何获取 Elastic 中每次出现的文档数量?

问题描述

我有一个弹性索引(比如file),每次客户端下载文件时,我都会在其中附加一个文档。每个文档都非常基础,它包含一个字段filename和一个日期when来指示下载时间。

我想要实现的是获取每个文件在过去 3 个月内下载的次数。

目前,我最接近这个查询:

{
    "query": {
        "range": {
            "when": {
                "gte": "now-3M"
            }
        }
    },
    "aggs": {
        "downloads": {
            "terms": {
                "field": "filename.keyword"
            }
        }
    }
}

结果是这样的:

{
    "took": 793,
    "timed_out": false,
    "_shards": {
        "total": 1,
        "successful": 1,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 10000,
            "relation": "gte"
        },
        "max_score": 1.0,
        "hits": [
            {
                "_index": "file",
                "_type": "_doc",
                "_id": "8DkTFHQB3kG435svAA3O",
                "_score": 1.0,
                "_source": {
                    "filename": "taz",
                    "id": 24009,
                    "when": "2020-08-21T08:11:54.943Z"
                }
            },
            ...
        ]
    },
    "aggregations": {
        "downloads": {
            "doc_count_error_upper_bound": 0,
            "sum_other_doc_count": 418486,
            "buckets": [
                {
                    "key": "file1",
                    "doc_count": 313873
                },
                {
                    "key": "file2",
                    "doc_count": 281504
                },
                ...,
                {
                    "key": "file10",
                    "doc_count": 10662
                }
            ]
        }
    }
}

所以我对 很感兴趣aggregations.downloads.bucket,但这仅限于 10 个结果。

我需要在查询中进行哪些更改才能获得所有列表(在我的情况下,我将拥有约 15,000 个不同的文件)?

谢谢。

标签: elasticsearch

解决方案


桶的默认size值为terms10。如果要增加它,请使用

{
    "query": {
        "range": {
            "when": {
                "gte": "now-3M"
            }
        }
    },
    "aggs": {
        "downloads": {
            "terms": {
                "field": "filename.keyword",
                "size": 15000          <-------
            }
        }
    }
}

请注意,有一些策略可以使用复合聚合对这些存储桶进行分页。

另请注意,随着索引的增长,您也可能会达到默认限制。这是一个动态集群范围的设置,因此可以更改


推荐阅读