2016-03-03 52 views
0

我存儲在elasticsearch下列文件嵌套過濾:Elasticsearch由Max

{ 
    run_number: 3, 
    vendor: v_a, 
    data: blah 
}, 
{ 
    run_number: 2, 
    vendor: v_b, 
    data: blah 
}, 
{ 
    run_number: 2, 
    vendor: v_b, 
    data: blah2 
}, 
{ 
    run_number: 1, 
    vendor: v_a, 
    data: blah 
}, 
{ 
    run_number: 1, 
    vendor: v_b, 
    data: blah 
} 

我試圖運行對這個返回的文件爲最近每個供應商運行搜索查詢。在這個例子中,我想返回前3個文檔(因爲它們具有給定供應商的最大'run_number')。

我的當前查詢是:

{ 
"size": 500, 
"aggs": { 
    "group_by_vendor": { 
     "terms": { 
      "field": "vendor" 
     }, 
     "aggs": { 
      "max_run_number": { 
       "terms": { 
        "field": "run_number", 
        "order": {"_term": "desc"}, 
        "size": 1 
       } 
      } 
     } 
    } 
} 
} 

但隨着尺寸= 1 max_run_number聚合不僅限制返回的嵌套桶。這仍然會返回所有匹配。

回答

1

使用top_hits這裏

{ 
"size": 0, 
"aggs": { 
"group_by_vendor": { 
    "terms": { 
     "field": "vendor" 
    }, 
    "aggs": { 
     "max_run_number": { 
      "terms": { 
       "field": "run_number", 
       "order": {"_term": "desc"}, 
       "size": 1 
      }, 
      "aggs" : { 
       "top hits agg" : { 
       "top_hits" : { 
       "size" :3 
       } 
       } 
      } 
     } 
     } 
    } 
    } 
    }