2017-03-31 34 views
0

我有一組文檔(帖子),它們在每篇文章中提到了一組用戶。Aggregate array occourances

{ 
    "title": "Some post title", 
    [ ... ] 
    "mentions": ["johnsmith", "johndoe", "paul"] 
} 

我想彙總唯一提及的列表以及它們在所有帖子中提及的次數。例如:

[{ user: "johnsmith", count: 5 }, { user: "benlewis", count: 9 }, { user: "johndoe", count: 1 }] 

隨着蒙戈,我會做一些事情,如:

"mentions": [{ 
    "$unwind": "$mentions" 
}, { 
    "$group": { 
     "_id": "$mentions", 
     "count": { "$sum": 1 } 
    } 
}] 

什麼是相當於Elasticsearch?

回答

0

您可以使用Terms聚合。小(5.x的)例如:

PUT test 
{ 
    "mappings": { 
    "test" : { 
     "properties": { 
     "title": { 
      "type": "text" 
     }, 
     "mentions": { 
      "type": "keyword" 
     } 
     } 
    } 
    } 
} 

POST test/test/1 
{ 
    "title": "Some post title", 
    "mentions": [ 
    "johnsmith", 
    "johndoe", 
    "paul" 
    ] 
} 

POST test/test/2 
{ 
    "title": "Some post title 2", 
    "mentions": [ 
    "johnsmith" 
    ] 
} 

GET test/_search 
{ 
    "size": 0, 
    "aggs": { 
    "test": { 
     "terms": { 
     "field": "mentions", 
     "size": 10 
     } 
    } 
    } 
} 

提供了以下回應:

"aggregations": { 
    "test": { 
     "doc_count_error_upper_bound": 0, 
     "sum_other_doc_count": 0, 
     "buckets": [ 
     { 
      "key": "johnsmith", 
      "doc_count": 2 
     }, 
     { 
      "key": "johndoe", 
      "doc_count": 1 
     }, 
     { 
      "key": "paul", 
      "doc_count": 1 
     } 
     ] 
    } 
    } 
} 

希望這有助於:)