Monday, July 12, 2010

Another way to do text search on MongoDB

I wrote an article on my main technology blog last November on doing indexing and search using MongoDB with the MongoRecord ORM style gem.

Since then, I have preferred to use MongoDB closer to the metal using the mongo gem (and using lower level interfaces when I develop in Clojure). Here is a simple example:
require 'rubygems' # only for Ruby 1.8.*
require 'mongo'

include Mongo

host = "localhost"
db = Connection.new(host,27017).db('my-db-name')
things = db.collection('things')

things.remove
things.insert('guid' => 102, :name => 'John Smith', :email => 'jsmith@example.com')
puts things.count
things.find(:name => /^john/i).each {|x| p x} # good performance
things.find(:name => /smith/i).each {|x| p x} # no so good performance
Because of the way indices are created, you should only do prefix wild card searches if you need good performance.

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.