Created
February 8, 2010 14:24
-
-
Save tty/298175 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
doc_col = MongoMapper.connection.db('example_db').collection('docs') | |
doc_col.remove({}) | |
doc_col.insert({ "txt" => "it is what it is"}) | |
doc_col.insert({ "txt" => "what is it"}) | |
doc_col.insert({ "txt" => "it is a banana"}) | |
map_index =<<JS | |
function() { | |
var words = this.txt.split(' '); | |
for ( var i=0; i<words.length; i++ ) { | |
emit(words[i], { docs: [this._id] }); | |
} | |
} | |
JS | |
reduce_index =<<JS | |
function(key, values) { | |
var docs = []; | |
values.forEach ( function(val) { docs = docs.concat(val.docs); }) | |
return { docs: docs }; | |
} | |
JS | |
map_relevance =<<JS | |
function() { | |
for ( var i=0; i< this.value.docs.length; i++ ) { | |
emit(this.value.docs[i], { count: 1 }); | |
} | |
} | |
JS | |
reduce_relevance=<<JS | |
function(key, values) { | |
var sum = 0; | |
values.forEach ( function(val) { sum += val.count; }) | |
return { count: sum }; | |
} | |
JS | |
#calculate the inverted index | |
invix_col = doc_col.map_reduce(map_index, reduce_index) | |
#calculate the # occcurances of each searchterm | |
query = ["what", "is", "it"] | |
ranked_result = invix_col.map_reduce(map_relevance, reduce_relevance, { :query => { "_id" => { "$in" => query} } } ) | |
#output the results, most relevant on top | |
ranked_result.find().sort("count", :desc).each do |result| | |
puts "document with id #{result["_id"]} has rank #{result["value"]["count"]} : #{doc_col.find_one("_id" => result["_id"]).inspect}" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment