elasticsearch - 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 个项目。我尝试了各种用于文档的东西,但它们似乎都不起作用。
解决方案
正如这个答案中已经建议的那样,您可以尝试在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"
}
}
}
}
}
}
}
}
这个问题广泛涵盖了随机排序。
希望有帮助!
推荐阅读
- android - 无法在 Play 控制台中打开应用程序进行测试
- android - 如何在微调器中将特定位置设置为默认位置?
- python - 使用 describe 和 dtypes 创建自定义函数时出错
- shopify - Shopify 将具有不同属性的多个产品添加到购物车
- c# - 依赖注入与构造函数重载
- ios - 尝试使用新电子邮件注册时收到错误消息“该电子邮件地址已被另一个帐户使用”
- javascript - 在javascript中使用时刻获取UTC日期
- python-3.x - 在 Cloud Functions 中对 Google Cloud Storage SDK 进行身份验证
- javascript - Vuejs有新消息时如何滚动到最新消息
- r - model.matrix 如何为交互项选择级别