即使是不成熟的尝试,也胜于胎死腹中的策略。

嵌套模型的统计脚本怎么同时计算嵌套字段和父字段

Elasticsearch | 作者 yjp | 发布于2018年08月07日 | 阅读数:2256

Elasticsearch Version: 5.6.3

映射如下:
PUT /my_stock
{
"mappings": {
"stock": {
"properties": {
"industry": {
"type": "nested",
"properties": {
"name": {
"type": "keyword"
},
"rate": {
"type": "double"
}
}
},
"changeRatio": {
"type": "double"
}
}
}
}

}


测试数据:


POST /_bulk
{"index":{"_index":"my_stock","_type":"stock","_id":null}}
{"industry":[{"name":"Technology","rate":0.6},{"name":"Health", "rate":0.2}],"changeRatio":0.1}
{"index":{"_index":"my_stock","_type":"stock","_id":null}}
{"industry":[{"name":"Health", "rate":0.3},{"name":"Education", "rate":0.2}],"changeRatio":0.2}
{"index":{"_index":"my_stock","_type":"stock","_id":null}}
{"industry":[{"name":"Health","rate":0.5},{"name":"Education","rate":0.2}],"changeRatio":-0.3}
{"index":{"_index":"my_stock","_type":"stock","_id":null}}
{"industry":[{"name":"Technology","rate":0.3},{"name":"Education","rate":0.3}],"changeRatio":0.4}
{"index":{"_index":"my_stock","_type":"stock","_id":null}}
{"industry":[{"name":"Education","rate":0.3},{"name":"Technology","rate":0.1}],"changeRatio":-0.5}


需求:按照行业涨跌率高低获取所有的行业
行业涨跌率=sum(股票的changeRatio * 股票占行业的比重industry.rate)
GET my_stock/stock/_search
{
"size": 0,
"aggs": {
"industry": {
"nested": {
"path": "industry"
},
"aggs": {
"groups": {
"terms": {
"field": "industry.name",
"order": {
"rate": "desc"
}
},
"aggs": {
"rate": {
"sum": {
"script": {
"source": "doc['changeRatio'].value * doc['industry.rate'].value"
}
}
}
}
}
}
}
}
}


这个查询方法中"doc['changeRatio'].value" 一直返回0 

另外一种查询方式:
GET my_stock/stock/_search
{
"size": 0,
"aggs": {
"industry": {
"nested": {
"path": "industry"
},
"aggs": {
"groups": {
"terms": {
"field": "industry.name",
"order":{
"reverse>rate":"desc"
}
},
"aggs": {
"reverse": {
"reverse_nested": {},
"aggs": {
"rate": {
"sum": {
"script": {
"source": "doc['changeRatio'].value * doc['industry.rate'].value"
}
}
}
}
}
}
}
}
}
}
}


"doc['changeRatio'].value"能够正常获取到, 但是 "doc['industry.rate'].value" 返回0了。

把doc替换成params._source结果是一样的
 
已邀请:

要回复问题请先登录注册