草庐IT

javascript - 从用户时间轴获取转推计数

coder 2023-11-03 原文

我使用 twitter api 'statuses/user_timeline' 将自己的 twitter tweets 集合存储在 mongodb 中。我正在尝试获取我使用 MongoDb MapReduce 方法发布的推文中的转推 计数,但无法获取。谁能帮帮我。

示例数据:这是存储在mongodb中的文档格式

{
    "_id" : ObjectId("570664d7a9c29761168b4587"),
    "created_at" : "Thu Sep 17 01:17:28 +0000 2015",
    "id" : NumberLong("644319222886039556"),
    "id_str" : "644319222886039556",
    "text" : "Be silent or let your words be worth more than you silence.",
    "entities" : {
        "hashtags" : [ ],
        "symbols" : [ ],
        "user_mentions" : [ ],
        "urls" : [ ]
    },
    "truncated" : false,
    "source" : "<a href=\"http://twitter.com\" rel=\"nofollow\">Twitter Web Client</a>",
    "in_reply_to_status_id" : null,
    "in_reply_to_status_id_str" : null,
    "in_reply_to_user_id" : null,
    "in_reply_to_user_id_str" : null,
    "in_reply_to_screen_name" : null,
    "user" : {
        // Here is the user information who tweeted
        "id" : NumberLong(xxxxxxxxxxxxxxxxx),
        "id_str" : "xxxxxxxxx",
        "name" : "Haridarshan Gorana",
        "screen_name" : "haridarshan2901"
    },
    "geo" : null,
    "coordinates" : null,
    "place" : null,
    "contributors" : null,
    "is_quote_status" : false,
    "retweet_count" : NumberLong(1),
    "favorite_count" : NumberLong(0),
    "favorited" : false,
    "retweeted" : false,
    "lang" : "en"
}

代码:

$map = new \MongoCode("function() { emit(this.id_str, this.retweet_count); }");
$out = "retweets";
$reduce = new \MongoCode('function(key, values) {
    var retweets = 0;
    for(i=0;i<values.length;i++){

        if( values[i].retweet_count > 0 ){
            retweets += values[i].retweet_count;
        }

    }
    return retweets;
}');
$verbose = true;
$cmd = array(
    "map" => $map,
    "reduce" => $reduce,
    "query" => $query,
    "out" => "retweets",
    "verbose" => true
);

$result = $db->command($cmd);

print_r($result);

这给了我这个错误

fatal error :在 null 上调用成员函数 command()

我尝试在 mongo 客户端上运行相同的代码

var mapFunction1 = function() {
    emit(this.id_str, this.retweet_count);
}

var reduceFunction1 = function(id, values) { 
    var retweet = 0; 
    for(i=0;i<values.length;i++){ 
        if(values[i].retweet_count > 0) { 
            retweet += values[i].retweet_count;
        } 
    } 
    return retweet;  
}

db.tweets.mapReduce(
    mapFunction1, 
    reduceFunction1, 
    {
        query: { 
            user: { id: xxxxxxxxx }
        }, 
        out: "retweets", 
        verbose: true
    }
)

控制台输出

{
    "result" : "retweets",
    "timeMillis" : 12,
    "timing" : {
        "mapTime" : 0,
        "emitLoop" : 8,
        "reduceTime" : 0,
        "mode" : "mixed",
        "total" : 12
    },
    "counts" : {
        "input" : 0,
        "emit" : 0,
        "reduce" : 0,
        "output" : 0
    },
    "ok" : 1
}

最佳答案

你的 reducer 正在尝试调用一个属性 retweet_count,而此时只有一个“值”而没有其他属性。您已经在映射器中引用了它。

实际上你的 reduce 可以简单地是:

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

但是您最好为此简单地使用 .aggregate()。它不仅更简单,而且运行速度更快:

db.tweets.aggregate([
  { "$group": {
    "_id": "$user.id_str",
    "retweets": { "$sum": "$retweet_count" }
  }}
])

或者对于 PHP

$collection->aggregate(
    array(
        '$group' => array(
           '_id' => '$user.id_str',
           'retweets' => array( '$sum' => '$retweet_count' )
        )
    )
)

如果您想向其中添加“查询”,请添加 $match管道阶段在开始。即

$collection->aggregate(
    array(
        '$match' => array(
            'user.id_str' => 'xxxxxxxxx'
        )
    ),    
    array(
        '$group' => array(
           '_id' => '$user.id_str',
           'retweets' => array( '$sum' => '$retweet_count' )
        )
    )
)

当结构实际需要 JavaScript 控制进行处理时,您真的应该只使用mapReduce

关于javascript - 从用户时间轴获取转推计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36496205/

有关javascript - 从用户时间轴获取转推计数的更多相关文章

  1. ruby-on-rails - 使用 rails 4 设计而不更新用户 - 2

    我将应用程序升级到Rails4,一切正常。我可以登录并转到我的编辑页面。也更新了观点。使用标准View时,用户会更新。但是当我添加例如字段:name时,它​​不会在表单中更新。使用devise3.1.1和gem'protected_attributes'我需要在设备或数据库上运行某种更新命令吗?我也搜索过这个地方,找到了许多不同的解决方案,但没有一个会更新我的用户字段。我没有添加任何自定义字段。 最佳答案 如果您想允许额外的参数,您可以在ApplicationController中使用beforefilter,因为Rails4将参数

  2. ruby-on-rails - Ruby 检查日期时间是否为 iso8601 并保存 - 2

    我需要检查DateTime是否采用有效的ISO8601格式。喜欢:#iso8601?我检查了ruby​​是否有特定方法,但没有找到。目前我正在使用date.iso8601==date来检查这个。有什么好的方法吗?编辑解释我的环境,并改变问题的范围。因此,我的项目将使用jsapiFullCalendar,这就是我需要iso8601字符串格式的原因。我想知道更好或正确的方法是什么,以正确的格式将日期保存在数据库中,或者让ActiveRecord完成它们的工作并在我需要时间信息时对其进行操作。 最佳答案 我不太明白你的问题。我假设您想检查

  3. ruby - 简单获取法拉第超时 - 2

    有没有办法在这个简单的get方法中添加超时选项?我正在使用法拉第3.3。Faraday.get(url)四处寻找,我只能先发起连接后应用超时选项,然后应用超时选项。或者有什么简单的方法?这就是我现在正在做的:conn=Faraday.newresponse=conn.getdo|req|req.urlurlreq.options.timeout=2#2secondsend 最佳答案 试试这个:conn=Faraday.newdo|conn|conn.options.timeout=20endresponse=conn.get(url

  4. ruby - 从 Ruby 中的主机名获取 IP 地址 - 2

    我有一个存储主机名的Ruby数组server_names。如果我打印出来,它看起来像这样:["hostname.abc.com","hostname2.abc.com","hostname3.abc.com"]相当标准。我想要做的是获取这些服务器的IP(可能将它们存储在另一个变量中)。看起来IPSocket类可以做到这一点,但我不确定如何使用IPSocket类遍历它。如果它只是尝试像这样打印出IP:server_names.eachdo|name|IPSocket::getaddress(name)pnameend它提示我没有提供服务器名称。这是语法问题还是我没有正确使用类?输出:ge

  5. ruby - 获取模块中定义的所有常量的值 - 2

    我想获取模块中定义的所有常量的值:moduleLettersA='apple'.freezeB='boy'.freezeendconstants给了我常量的名字:Letters.constants(false)#=>[:A,:B]如何获取它们的值的数组,即["apple","boy"]? 最佳答案 为了做到这一点,请使用mapLetters.constants(false).map&Letters.method(:const_get)这将返回["a","b"]第二种方式:Letters.constants(false).map{|c

  6. ruby-on-rails - 将 Ruby 中的日期/时间格式化为 YYYY-MM-DD HH :MM:SS - 2

    这个问题在这里已经有了答案:Railsformattingdate(4个答案)关闭4年前。我想格式化Time.Now函数以显示YYYY-MM-DDHH:MM:SS而不是:“2018-03-0909:47:19+0000”该函数需要放在时间中.现在功能。require‘roo’require‘roo-xls’require‘byebug’file_name=ARGV.first||“Template.xlsx”excel_file=Roo::Spreadsheet.open(“./#{file_name}“,extension::xlsx)xml=Nokogiri::XML::Build

  7. ruby - 查找字符串中的内容类型(数字、日期、时间、字符串等) - 2

    我正在尝试解析一个CSV文件并使用SQL命令自动为其创建一个表。CSV中的第一行给出了列标题。但我需要推断每个列的类型。Ruby中是否有任何函数可以找到每个字段中内容的类型。例如,CSV行:"12012","Test","1233.22","12:21:22","10/10/2009"应该产生像这样的类型['integer','string','float','time','date']谢谢! 最佳答案 require'time'defto_something(str)if(num=Integer(str)rescueFloat(s

  8. ruby-on-rails - 获取 inf-ruby 以使用 ruby​​ 版本管理器 (rvm) - 2

    我安装了ruby​​版本管理器,并将RVM安装的ruby​​实现设置为默认值,这样'哪个ruby'显示'~/.rvm/ruby-1.8.6-p383/bin/ruby'但是当我在emacs中打开inf-ruby缓冲区时,它使用安装在/usr/bin中的ruby​​。有没有办法让emacs像shell一样尊重ruby​​的路径?谢谢! 最佳答案 我创建了一个emacs扩展来将rvm集成到emacs中。如果您有兴趣,可以在这里获取:http://github.com/senny/rvm.el

  9. Ruby 从大范围中获取第 n 个项目 - 2

    假设我有这个范围:("aaaaa".."zzzzz")如何在不事先/每次生成整个项目的情况下从范围中获取第N个项目? 最佳答案 一种快速简便的方法:("aaaaa".."zzzzz").first(42).last#==>"aaabp"如果出于某种原因你不得不一遍又一遍地这样做,或者如果你需要避免为前N个元素构建中间数组,你可以这样写:moduleEnumerabledefskip(n)returnto_enum:skip,nunlessblock_given?each_with_indexdo|item,index|yieldit

  10. ruby-on-rails - Ruby on Rails 计数器缓存错误 - 2

    尝试在我的RoR应用程序中实现计数器缓存列时出现错误Unknownkey(s):counter_cache。我在这个问题中实现了模型关联:Modelassociationquestion这是我的迁移:classAddVideoVotesCountToVideos0Video.reset_column_informationVideo.find(:all).eachdo|p|p.update_attributes:videos_votes_count,p.video_votes.lengthendenddefself.downremove_column:videos,:video_vot

随机推荐