mongodb ruby本机驱动程序中的Mapreduce [英] Mapreduce in mongodb ruby native driver
本文介绍了mongodb ruby本机驱动程序中的Mapreduce的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在为mongodb使用本机ruby驱动程序.我想以此执行地图缩减功能,我尝试按此链接给出
I am using native ruby driver for mongodb.I want to perform map reduce function with that and i tried given as per this link 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的新手. 请帮我.
How to achieve this.I am new learner to ruby and mongodb. Please help me.
推荐答案
我知道了原因,我的新代码是
I figured out the reason and my new code is
# 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
在选择中,我需要给出和raw.i来回链接 此处
In opts i need to give the out and raw.i got fro the link here
此代码运行正常. 谢谢.
This code is working fine. Thanks.
这篇关于mongodb ruby本机驱动程序中的Mapreduce的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文