elasticsearch - 嵌套聚合返回计数值桶的弹性搜索查询是什么?
问题描述
我在 Elastic Search 中有个人客户的数据,他们对 Food_Item 的喜好存储如下所示。客户喜欢许多“Food_Items”。所以它是一个列表。我也有很多客户。
我有以下格式的数据:
{
"id": 1,
"customerName":"John",
"likings":[
{
"Food_Item": "Pizza",
"OnAScaleOfTen": 9
},
{
"Food_Item": "Chinese",
"OnAScaleOfTen": 10
}
]
},
{
"id": 2,
"customerName":"Mary",
"likings":[
{
"Food_Item": "Burger",
"OnAScaleOfTen": 10
},
{
"Food_Item": "Chinese",
"OnAScaleOfTen": 6
}
]
}
现在,如果我想在AGGR结果中列出唯一的“Food_Items”及其相应的计数,如下所示:
"Liking_Status": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [
{
"key": "Chinese",
"Liking Count": {
"value": 2
}
},
{
"key": "Pizza",
"Liking Count": {
"value": 1
}
},
{
"key": "Burger",
"Liking Count": {
"value": 1
}
}]}
我的索引映射是:
{
"mappings": {
"doc": {
"properties": {
"customerName": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"id": {
"type": "long"
},
"likings": {
"type":"nested",
"properties": {
"Food_Item": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"OnAScaleOfTen": {
"type": "long"
}
}
}
}
}
}
}
任何人都可以帮助我使用弹性搜索查询。谢谢你。
解决方案
您需要的是嵌套聚合。
{
"size": 0,
"aggs": {
"buckets": { //aggregating on nested field
"nested": {
"path": "likings"
},
"aggs": {
"liking_count": {//term aggregation on the obj
"terms": {
"field": "likings.Food_Item.keyword"
}
}
}
}
}
}
映射:
我刚刚提到它likings
是嵌套的。除了其他都是默认的。在这种情况下,Food_Item 是一个文本。术语 aggs 适用于关键字。所以从索引中使用了它的关键字版本。
输出:
"aggregations": {
"buckets": {
"doc_count": 4,
"liking_count": { //You can name what you want here
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [
{
"key": "Chinese",
"doc_count": 2
},
{
"key": "Burger",
"doc_count": 1
},
{
"key": "Pizza",
"doc_count": 1
}
]
}
}
}
推荐阅读
- javascript - 扩展 SVG.Element 的更好方法,让 vscode 知道已进行更改并提供文档
- javascript - 在迭代两个时对数组进行排序?
- excel - VBA 循环复制、粘贴和执行其他 VBA
- python - 优化代码:仅返回 python 列表的最高版本文件名
- google-cloud-platform - GCP Cloud SDK 在 MAC 中安装失败
- python - wxPython 网格小部件底部和网格边框内的不需要的空间
- angular - 在 Angular 中使用 FontAwesome Pro
- laravel - Laravel show 方法输出空对象
- python - 在 python trie 中存储字数
- reactjs - 减速器未执行