elasticsearch - 使用嵌套对象数组对索引进行 ElasticSearch 查询和过滤
问题描述
我有一个具有以下文档结构的 ElasticSearch 索引设置
[
{
"id":id,
"title: "Sample Title",
"created_at":timestamp
"categories:[
{
"name": "Category 1"
"image": "image.png",
},
{
"name": "Category 2"
"image": "image.png",
},
{
"name": "Category 3"
"image": "image.png",
},
{
"name": "Category 4"
"image": "image.png",
},
....
]
},
....
]
该索引将包含数十万条这种格式的记录。我正在尝试弄清楚如何以最佳方式设置查询并构建此数据,以便我可以设置一个查询,使我能够以这种方式向最终用户显示类别列表。
- [图片] 类别 1 (20)
- [图片] 类别 2 (30)
- [图片] 类别 3 (10)
此查询将能够通过 created_at 时间戳过滤,以便根据此类项目的数量调整计数。
- [图片] 类别 1 (10)
- [图片] 类别 2 (5)
- [图片] 类别 3 (25)
解决方案
终于想通了。
首先,您必须为类别显式设置映射,否则将不允许您在聚合中使用“嵌套”属性。
"mappings": {
"dynamic": "true",
"properties":{
"categories":{
"type":"nested"
}
}
}
然后我发现解决这个问题的最佳方法是使用“复合”聚合https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-composite-aggregation.html
这将允许我对聚合进行分页并拉回所有必要的属性。
{
"aggs": {
"categories": {
"nested": {
"path": "categories"
},
"aggs": {
"list": {
"composite": {
"sources": [
{
"name": {
"terms": {
"field": "categories.name.keyword"
}
}
},
{
"image": {
"terms": {
"field": "categories.image.keyword"
}
}
}
]
}
}
}
}
}
}
推荐阅读
- xgboost - MLflow 是否支持分布式 XGBoost 模型?
- python - 值错误:多元线性回归模型中的形状未对齐
- python - Turtle Tk 主循环
- javascript - onCLick() 选项和选择问题
- spring-boot - Spring boot + lettuce 连接重试机制实现“Connection reset by peer”
- spring - 我在eclipse中使用Jdk 14,maven java版本POM.XML文件是什么
- jquery - 如果选择了 2 个单独的无线电输入。做一点事
- c# - 尝试使用 DataRowView 访问时,DataGrid 的 WPF-DataGridTemplate 列在后面的代码中不可用
- python - 与多行循环相比,单行循环是否节省了 python 代码的运行时间?
- kotlin - 如何表达对实现接口的 lambda 的“this”引用?