2014-12-25 49 views
0

我有一些鸣叫下载到我的MongoDB。 在Twitter上发布的文件看起来是这样的:MongoDB鸣叫标签符合计数

{ 
    "_id" : NumberLong("542499449474273280"), 
    "retweeted" : false, 
    "in_reply_to_status_id_str" : null, 
    "created_at" : ISODate("2014-12-10T02:02:02Z"), 
    "hashtags" : [ 
     "Canucks", 
     "allhabs", 
     "GoHabsGo" 
    ] 
    ... 
} 

我想构建一个查询/汇聚/地图,减少,这将使我有相同的两个哈希标签鸣叫的次数。对于每一对不相等的主题标签它给了我

{'count': 12, 'pair': ['malaria', 'Ebola']} 
{'count': 1, 'pair': ['Nintendo', '8bit']} 
{'count': 1, 'pair': ['guinea', 'Ebola']} 
{'count': 1, 'pair': ['fitness', 'HungerGames']} 
... 

我做了一个python脚本来做到这一点的鸣叫例如:的计数:

hashtags = set() 

tweets = db.tweets.find({}, {'hashtags':1}) 
#gather all hashtags from every tweet 
for t in tweets: 
    hashtags.update(t['hashtags']) 

hashtags = list(hashtags) 

hashtag_count = [] 
for i, h1 in enumerate(hashtags): 
    for j, h2 in enumerate(hashtags): 
     if i > j: 
      count = db.tweets.find({'hashtags' : {'$all':[h1,h2]}}).count() 
      if count > 0: 
       pair = {'pair' : [h1, h2], 'count' : count} 
       print(couple) 
       db.hashtags_pairs.insert(pair) 

但我想让它只是一个查询或JS函数使用map-reduce。 任何想法?

回答

0

没有任何聚合管道或查询可以从给定的文档结构中计算出来,所以如果您不想大幅度更改集合结构或构建二级集合,则必须使用map/reduce。但是,映射/缩减很简单:在映射阶段,为文档中的每个hashtags对发射一对(pair of hashtags, 1),然后在缩小阶段对每个键的值进行求和。

var map = function() { 
    var tags = this.tags; 
    var k = tags.length; 
    for (var i = 0; i < k; i++) { 
     for (var j = 0; j < i; j++) { 
      if (tags[i] != tags[j]) { 
       var ts = [tags[i], tags[j]].sort(); 
       emit({ "t0" : ts[0], "t1" : ts[1] }, 1) 
      } 
     } 
    } 
} 

var reduce = function(key, values) { return Array.sum(values) }