Skip to content

Instantly share code, notes, and snippets.

@alonecuzzo
Created November 28, 2011 18:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alonecuzzo/1401446 to your computer and use it in GitHub Desktop.
Save alonecuzzo/1401446 to your computer and use it in GitHub Desktop.
full text search, multi indexing mongo - ruby
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