2

am I correct in that MongoDB map/reduce feature is not available on Mongoid Criteria for MongoId version 2+

Can any one confirm this I have a criteria

Here my Query

class PerformerSource
  scope :active_performers,where(:active => true).only([:performer_id, :sort_order,:stage_name, :photo, :large_photo, :status, :current_performance_type,:current_sign_in_at])
end

PerformerSource.active_performers.order_by([:sort_order,:desc])

I want to apply map/reduce function to it

something like this

PerformerSource.active_performers.order_by([:sort_order,:desc]).map_reduce(PerformerSource.map,PerformerSource.reduce)

but whenever I do this it return with error

NoMethodError: undefined method `map_reduce' for #

Checking if the map/reduce is available at all

PerformerSource.active_performers.order_by([:sort_order,:desc]).respond_to?(:map_reduce)
=> false

PerformerSource.respond_to?(:map_reduce)
=> false

So am I correct in my believe since I see Mongoid-3 has a provision of adding map/reduce in Mongoid-criteria over here but cant find the same in mongoid 2

I can upgrade mongoid (I wish I could) since the application is running on Ruby-1.8.7 and mongoid 3 required ruby-1.9+

So can let me if the map/reduce wont work on criteria how to run the map/reduce then taking the other conditions in account i.e active_performers.order_by([:sort_order,:desc])

Note: I just for clarity in haven't added the map and reduce function

Ratatouille
  • 1,372
  • 5
  • 23
  • 50

1 Answers1

2

I have produced the following monkey patch, which I'm using in production:


module Mongoid

  module Criterion #:nodoc:
    module MapReduce
      def map_reduce(map, reduce, options = {})
        opts = {:out => {:inline => 1}, :raw => true, :query => selector}.merge(options)
        klass.collection.map_reduce(map, reduce, opts)
      end
      alias :mapreduce :map_reduce
    end
  end

end

This way I can execute map-reduce on a criteria. And if you want to execute it on all, then either use .all or .scoped (which I prefer), like PerformerSource.scoped.map_reduce(..)

Roman
  • 13,100
  • 2
  • 47
  • 63
  • I doubt it will fire a based on the criteria append to it like `Performer.active_performers.order_by([:sort_order,:desc]).map_reduce' correct me if I'm wrong – Ratatouille Oct 19 '12 at 04:15
  • I didn't really understand what you have said here. BTW, the order really makes little sense unless you limit the number of results. – Roman Oct 19 '12 at 10:33
  • I said you are appending a map reduce function what will `klass.collection` would return the result `Performer.active_performers.order_by([:sort_order,:desc])` of the criteria that define and then operate map-reduce on it further the criteria after map_reduce will that work – Ratatouille Oct 23 '12 at 09:39
  • klass.collection.map_reduce receives the original selector as a :query parameter. – Roman Oct 23 '12 at 14:35