Skip to content

Instantly share code, notes, and snippets.

@syntruth
Last active August 29, 2015 14:07
Show Gist options
  • Save syntruth/3aa27089520932d6c551 to your computer and use it in GitHub Desktop.
Save syntruth/3aa27089520932d6c551 to your computer and use it in GitHub Desktop.
MongoDB Tree MapReduce
# Encoding: UTF-8
# This defined a way to do a Map/Reduce search
# in MongoDB to find all service groups that has
# a given device in either the TX or RX path tree.
module ServiceGroupPathSearch
extend ActiveSupport::Concern
included do
class_eval do
def self.path_search(node)
mfunc = path_search_map
rfunc = path_search_reduce
args = { out: 'path_search', scope: { search_name: node.name } }
cursor = self.collection.map_reduce(mfunc, rfunc, args).find()
find cursor.first['value']['ids']
end
def self.path_search_map
<<-MAP
function mapFunc() {
function hasName(path) {
if (path.name == search_name) return true;
if (!path.children || !path.children.length) return false;
for (var idx = 0; idx < path.children.length; idx++) {
good = hasName(path.children[idx]);
if (good) return true;
}
return false;
}
if (hasName(this.tx) || hasName(this.rx)) {
emit('paths', { id: this._id });
}
}
MAP
end
def self.path_search_reduce
<<-REDUCE
function reduceFunc(id, values) {
var data = { ids: [] };
for (idx in values) {
data.ids.push(values[idx].id)
}
return data;
}
REDUCE
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment