gpt4 book ai didi

mongodb - Twitter 数据 - 在 MongoDB 中查找提及次数最多的用户

转载 作者:可可西里 更新时间:2023-11-01 10:05:40 27 4
gpt4 key购买 nike

假设我有来自 Twitter API 的流数据,并且我将数据作为文档存储在 MongoDB 中。我要查找的是 entities.user_mentions 下的 screen_name 的计数。

{
"_id" : ObjectId("50657d5844956d06fb5b36c7"),
"contributors" : null,
"text" : "",
"entities" : {
"urls" : [ ],
"hashtags" : [
{
"text" : "",
"indices" : [
26,
30
]
},
{
"text" : "",
"indices" : []
}
],
"user_mentions" : [
{
"name":"Twitter API",
"indices":[4,15],
"screen_name":"twitterapi",
"id":6253282, "id_str":"6253282"
}]
},
...

我尝试使用 map reduce:

map = function() {
if (!this.entities.user_mentions.screen_name) {
return;
}

for (index in this.entities.user_mentions.screen_name) {
emit(this.entities.user_mentions.screen_name[index], 1);
}
}

reduce = function(previous, current) {
var count = 0;

for (index in current) {
count += current[index];
}

return count;
}

result = db.runCommand({
"mapreduce" : "twitter_sample",
"map" : map,
"reduce" : reduce,
"out" : "user_mentions"
});

但它不是很有效...

最佳答案

由于 entities.user_mentions 是一个数组,您希望在 map() 中为每个 screen_name 发出一个值:

var map = function() {
this.entities.user_mentions.forEach(function(mention) {
emit(mention.screen_name, { count: 1 });
})
};

然后在 reduce() 中按唯一的 screen_name 计算值:

var reduce = function(key, values) {
// NB: reduce() uses same format as results emitted by map()
var result = { count: 0 };

values.forEach(function(value) {
result.count += value.count;
});

return result;
};

注意:要调试 map/reduce JavaScript 函数,您可以使用 print()printjson() 命令。输出将出现在您的 mongod 日志中。

编辑:为了比较,这里有一个使用新的 Aggregation Framework 的例子在 MongoDB 2.2 中:

db.twitter_sample.aggregate(
// Project to limit the document fields included
{ $project: {
_id: 0,
"entities.user_mentions" : 1
}},

// Split user_mentions array into a stream of documents
{ $unwind: "$entities.user_mentions" },

// Group and count the unique mentions by screen_name
{ $group : {
_id: "$entities.user_mentions.screen_name",
count: { $sum : 1 }
}},

// Optional: sort by count, descending
{ $sort : {
"count" : -1
}}
)

原始的 Map/Reduce 方法最适合大型数据集,正如 Twitter 数据所暗示的那样。有关 Map/Reduce 与聚合框架限制的比较,请参阅 StackOverflow 问题的相关讨论 MongoDB group(), $group and MapReduce .

关于mongodb - Twitter 数据 - 在 MongoDB 中查找提及次数最多的用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12654451/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com