Advanced Rails - Building Industrial-Strength Web Apps in Record Time

(Tuis.) #1

170 | Chapter 6: Performance


Jens Krämer’s acts_as_ferret library (http://projects.jkraemer.net/acts_as_ferret/)
makes it quite a bit easier to use Ferret to search an ActiveRecord model. The basic
procedure is as follows:



  1. Install the Ferret library as a gem:
    $ sudo gem install ferret

  2. Install acts_as_ferret as a Rails plugin:
    $ script/plugin install \
    svn://projects.jkraemer.net/acts_as_ferret/tags/stable/acts_as_ferret

  3. Add theacts_as_ferretcall to any model that should be indexed. The:remote =>
    trueoption directs acts_as_ferret to connect to a central Ferret server over DRb;
    this option is required when using multiple application servers:
    class Product < ActiveRecord::Base
    acts_as_ferret :fields => [:title, :description, :product_number],
    :remote => true
    end

  4. Use thefind_by_contents class method to query the index:
    results = Product.find_by_contents "toaster"

  5. If a manual reindex is necessary, use therebuild_index class method:
    Product.rebuild_index


For those of us who are only killing flies, and thus don’t need a sledgehammer,
Mauricio Fernández has a solution: FTSearch. Although it does not have many of
the features that Ferret provides, it is much lighter (about 3% of the size, as measured in
lines of code) and it has the most commonly used features. FTSearch is available from
http://eigenclass.org/hiki/ftsearch+repository+accessible, and Mauricio has a technical
description athttp://eigenclass.org/hiki.rb?simple+full+text+search+engine.


Spatial indexes


Spatial data has a completely different set of requirements than other data, owing
primarily to the types of queries that are typically made against it. Even simple spa-
tial queries can turn into expensive computational geometry problems.


All major DBMSs have some sort of module for working with spatial data: PostGIS,
MySQL Spatial Extensions, Oracle Spatial, and DB2 Spatial Extender. Most com-
monly, these modules use R-tree indexes to categorize spatial objects in the data-
base. As with any index, defining R-tree indexes must be done manually and takes
some skill. As always, consult your DBMS manual for details.


As usual, there is a lighter-touch option available. The GeoKit library (http://geokit.
rubyforge.org/) can work with latitude and longitude columns in an ordinary database,
doing distance calculations for you. This is great for simple applications that involve a
bit of geospatial data, such as store locators (made possible by GeoKit’s distance-based
ActiveRecord finders and automatic interface to geocoding web services):


Store.find :all, :origin => '60685', :within => 10, :order => 'distance asc'
Free download pdf