在Elasticsearch中,我们可以使用聚合框架和脚本来实现按照其他参考文档中数组特定字段的求和进行文档排序。
以下为示例代码:
在mapping中设置参考文档的关联:
PUT my_index
{
"mappings": {
"properties": {
"category": {
"type": "keyword"
},
"items": {
"type": "nested",
"properties": {
"itemId": {
"type": "long"
},
"quantity": {
"type": "integer"
},
"productId": {
"type": "long"
}
}
}
}
}
}
插入一些测试数据:
PUT my_index/_doc/1
{
"category": "books",
"items": [
{ "itemId": 1, "productId": 100, "quantity": 2 },
{ "itemId": 2, "productId": 101, "quantity": 3 },
{ "itemId": 3, "productId": 102, "quantity": 4 }
]
}
PUT my_index/_doc/2
{
"category": "books",
"items": [
{ "itemId": 4, "productId": 103, "quantity": 1 },
{ "itemId": 5, "productId": 104, "quantity": 5 }
]
}
PUT my_index/_doc/3
{
"category": "music",
"items": [
{ "itemId": 6, "productId": 200, "quantity": 3 }
]
}
使用脚本计算每个文档items数组中quantity字段的和:
GET my_index/_search
{
"size": 0,
"aggs": {
"category_agg": {
"terms": {
"field": "category"
},
"aggs": {
"total_quantity": {
"scripted_metric": {
"init_script": "state.sum = new java.math.BigDecimal