Created
November 28, 2011 18:35
-
-
Save alonecuzzo/1401446 to your computer and use it in GitHub Desktop.
full text search, multi indexing mongo - ruby
This file contains 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
class Recipe < MongoRecord::Base | |
collection_name :recipes | |
fields :name, :directions, :words | |
def to_s | |
"recipe: #{name} directions: #{directions[0..20]}..." | |
end | |
def Recipe.make collection, name, directions | |
collection.insert({:_id => Mongo::ObjectID.new, :name => name, | |
:directions => directions, | |
:words => (name + ' ' + directions).split.uniq}) | |
end | |
end | |
host = 'localhost' | |
port = Mongo::Connection::DEFAULT_PORT | |
MongoRecord::Base.connection = Mongo::Connection.new(host,port).db('mongorecord-test') | |
db = MongoRecord::Base.connection | |
coll = db.collection('recipes') | |
coll.remove({}) | |
coll.create_index(:words, Mongo::ASCENDING) | |
Recipe.make coll, 'Rice Soup', 'Cook the rice, then add extra water to thin it out.' | |
Recipe.make coll, 'Cheese and Rice Crackers', 'Slice the cheese and layer on top of crackers.' | |
puts "\nSimple find" | |
puts Recipe.find_by_name(:name => 'Rice Soup').to_s | |
puts "\nFind recipe by regular expression (ignoring case) in array of words /water/i" | |
Recipe.find(:all, :conditions => {:words => /^water/i}).each { |row| puts row.to_s } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment