Mapreduce在mongodb ruby​​本机驱动程序中

时间:2013-12-29 14:26:12

标签: ruby mongodb

我正在使用mongodb的原生ruby驱动程序。我想用它执行map reduce功能,我尝试按照此链接here给出。

我收到了错误状态undefined method last for nil:NilClass

我尝试的代码是

def self.mapreduce
    begin
    # remove old decoments
    DBEngine.remove_alldocuments(COLLECTION_MAPREDUCE)
    # sample collection insertion to perform map reduce function
    3.times do |ctr|
    document = {
    "cust_id" => "A12",
    "amount"    => 200,
    "status"    => "S"              
    }
    result = DBEngine.insert(COLLECTION_MAPREDUCE,document)
    puts result
    end
    2.times do |ctr|
    document = {
    "cust_id" => "A13",
    "amount"    => 250,
    "status"    => "S"
    }
    result = DBEngine.insert(COLLECTION_MAPREDUCE,document)
    puts result         
    end

    @map = "function(){" +
    "emit(this.cust_id,this.amount);" +
    "}; "
    @reduce = "function(key,values){" +
    "return Array.sum(values);" +
    "}"
    @query =    {
    :query => 
    {
    "status" => "S"
    }
    }           

    result = COLLECTION_MAPREDUCE.map_reduce(@map,@reduce,@query)
    puts result
    rescue Exception => e
    puts e
    end
    end

如何实现这一目标。我是ruby和mongodb的新学徒。 请帮我。

1 个答案:

答案 0 :(得分:1)

我弄明白了原因,我的新代码是

# Map function which emits the two necessary fileds like key and value to perform our operations
    map = "function(){" +
    "emit(this.cust_id,this.amount);" +
    "}; "

    # Reduce function reduces the values as per logic and outputs with key and value
    reduce = "function(key,values){" +
    "return Array.sum(values);" +
    "}"

    # Check this link fore reference :- http://www.rubydoc.info/github/mongodb/mongo-ruby-driver/master/Mongo/Collection:map_reduce
    # a customizable set of options to perform map reduce functions
    opts =  {
    :query => 
    {
    "status" => "S"
    },
    # out specifies where we need to output the map reduce output.
    # if we specify simply a name in string like "order_totals" it creates a collection in that name 
    # and stores in that
    # if we need to store in a temp memory and needed as output we need to give {:inline => 1} ans
    # :raw => true
    # check link :- http://docs.mongodb.org/manual/reference/command/mapReduce/#mapreduce-out-cmd
    :out => {:inline => 1}, 
    :raw => true
    }           

    result = COLLECTION_MAPREDUCE.map_reduce(map,reduce,opts)
    result["results"].each do |obj|
    puts obj    
    puts "\n ------------"
    end

在opts中,我需要提供out和raw.i从链接中获取 here

此代码工作正常。 感谢。