2016-04-01 95 views
1

下面是例子文件:如何聚集在top_hits結果elasticsearch

{ 
    "player": "Jim", 
    "score" : 5 
    "timestamp": 1459492890000 
} 

{ 
    "player": "Jim", 
    "score" : 7 
    "timestamp": 1459492895000 
} 

{ 
    "player": "Dave", 
    "score" : 9 
    "timestamp": 1459492894000 
} 

{ 
    "player": "Dave", 
    "score" : 4 
    "timestamp": 1459492898000 
} 

我想每個球員的最新得分,然後讓所有這些成績的平均值。所以答案是5.5。吉姆的最新成績是7分,戴夫的最新成績是4.這兩人的平均分數是5.5

我發現獲得玩家「最新」文檔的唯一方法是使用top_hits聚合。但是,在獲得最新文檔後,我似乎無法再進行聚合。

這是最好的,我想出了:

{ 
    "aggs": { 
    "last_score": { 
     "terms": { "field": "player" }, 
     "aggs": { 
     "last_score_hits": { 
      "top_hits": { 
      "sort": [ { "timestamp": { "order": "desc" } } ], 
      "size": 1 
      }, 
      "aggs": { 
      "avg_score": { 
       "avg": { "field": "score" } 
      } 
      } 
     } 
     } 
    } 
    } 
} 

然而,這給了我這個錯誤:

Aggregator [last_score_hits] of type [top_hits] cannot accept sub-aggregations

如果有另一種方式來實現這一目標的搜索,而無需使用top_hits爲好,那麼我會全力以赴。

回答

0

您正在嘗試將avg_score作爲last_score_hits的子集合。 要取得成功,您必須將avg_score作爲last_score的子彙總。看到一個示例波紋管:

{ 
    "aggs": { 
    "last_score": { 
     "terms": { 
     "field": "player" 
     }, 
     "aggs": { 
     "last_score_hits": { 
      "top_hits": { 
      "sort": [ 
       { 
       "timestamp": { 
        "order": "desc" 
       } 
       } 
      ], 
      "size": 1 
      } 
     }, 
     "avg_score": { 
      "avg": { 
      "field": "score" 
      } 
     } 
     } 
    } 
    } 
} 
+0

我不認爲這是OP想要的。 –