我有一个名为 socialmedia 的索引,并尝试使用名为 eng 的该字段创建查询(省略了一些不必要的字段)
"id" : "1",
"eng":
[
{
"soc_mm_score" : "3",
"date_updated" : "1520969306",
},
{
"soc_mm_score" : "1",
"date_updated" : "1520972191",
},
{
"soc_mm_score" : "4",
"date_updated" : "1520937222",
}
]
此索引中有很多个文档,其中包含 eng 嵌套字段,其中还包含很多“子对象”
现在,我的主要目标是,我应该制定什么样的Elasticsearch查询来过滤掉这些嵌套对象
STEP 1
获取具有最高 date_updated 值
第2步
在获得这些嵌套对象之后,执行一次 sum 聚合,以便为相应的“最新嵌套对象” 添加 soc_mm_score 字段的所有值。
我已经尝试过该查询,但似乎失败了
ATTEMPT#1 (我使用的是Elasticsearch-php API,因此请相信我的查询,它可以使用这种格式)
'aggs' => [
'ENG' => [
'nested' => [
'path' => 'eng'
],
'aggs' => [
'FILTER' => [
'filter' => [
'bool' => [
'must' => [
[
// I'm thinking of using max aggregation here
]
]
]
]
]
'LATEST' => [
'top_hits' => [
'size' => 1,
'sort' => [
'eng.date_updated' => [
'order' => 'desc'
]
]
]
]
]
]
]
PRO / S:它返回正确的嵌套对象 CON / S:我无法进行进一步的汇总
还有其他方法可以执行此操作吗?
回顾我理想的步骤:
答案 0 :(得分:4)
制定了答案!
"aggs":{
"LATEST": {
"scripted_metric": {
"init_script" : """
state.te = [];
state.g = 0;
state.d = 0;
state.a = 0;
""",
"map_script" : """
if(state.d != doc['_id'].value){
state.d = doc['_id'].value;
state.te.add(state.a);
state.g = 0;
state.a = 0;
}
if(state.g < doc['eng.date_updated'].value){
state.g = doc['eng.date_updated'].value;
state.a = doc['eng.soc_te_score'].value;
}
""",
"combine_script" : """
state.te.add(state.a);
double count = 0;
for (t in state.te) {
count += t
}
return count
""",
"reduce_script" : """
double count = 0;
for (a in states) {
count += a
}
return count
"""
}
}
}