Incredible what a few lines of Ruby code will do
Ruby, with great libraries like ActiveRecord and Ferret let you solve problems with just a few lines of code. I had 4 database tables that I wanted to index all fields of each row, and enable a plain text search that would quickly point me back to the table name and row index. The indexing takes about 20 lines of code and took less than 10 minutes to get working:
This would take a lot of code in Java, Common Lisp, etc. Unless my customers specifically ask me to use another programming language, I just about always use Ruby now.
class CreateIndex
def initialize
@index = Ferret::Index::Index.new(:path => './search_index')
ActiveRecord::Base.establish_connection(
:adapter => 'postgresql',
:host => 'localhost',
:username => 'postgres',
:database => 'test_database')
process_class(Item)
process_class(Plan)
process_class(Procedure)
process_class(Visit)
@index.close
end
def process_class the_class
the_class.find_all.each {|obj|
doc1 = Document.new
doc1 << Field.new("text", obj.attributes.values.join(' '), Field::Store::YES, Field::Index::TOKENIZED)
doc1 << Field.new("class", the_class.to_s, Field::Store::YES, Field::Index::NO)
doc1 << Field.new("id", obj.id.to_s, Field::Store::YES, Field::Index::NO)
@index << doc1
}
end
end
Comments
Post a Comment