首页 > 解决方案 > ElasticSearch 返回聚合随机顺序

问题描述

我有以下 ElasticSearch 查询,可以从每个“类别”中获取 10 个文档,这些文档按“cat.id”分组:

"aggs": {
    "test": {
        "terms": {
            "size": 10,
            "field": "cat.id"
        },
        "aggs": {
            "top_test_hits": {
                "top_hits": {
                    "_source": {
                        "includes": [
                            "id"
                        ]
                    },
                    "size": 10
                }
            }
        }
    }
}

这工作正常。但是我似乎无法找到一种方法,从每个桶中随机抽取 10 个结果。结果总是一样的。我想从每个桶中随机抽取 10 个项目。我尝试了各种用于文档的东西,但它们似乎都不起作用。

标签: elasticsearch

解决方案


正如这个答案中已经建议的那样,您可以尝试在top_hits聚合中使用随机排序,使用_script如下:

{
  "aggs": {
    "test": {
      "terms": {
        "size": 10,
        "field": "cat.id"
      },
      "aggs": {
        "top_test_hits": {
          "top_hits": {
            "_source": {
              "includes": [
                "id"
              ]
            },
            "size": 10,
            "sort": {
              "_script": {
                "type": "number",
                "script": {
                  "lang": "painless",
                  "source": "(System.currentTimeMillis() + doc['_id'].value).hashCode()"
                },
                "order": "asc"
              }
            }
          }
        }
      }
    }
  }
}

这个问题广泛涵盖了随机排序。

希望有帮助!


推荐阅读