On-the-floor

On the Floor

Add Search to Ruby on Rails Projects with acts_as_xapian

I recently built a search in a project using acts_as_xapian, and was quite impressed by the speed of the search, as well as the flexibility in setting things up... once I understood the documentation.  
Here's a summary of what I found.  Hope it helps someone!

 

How to install xapian and acts_as_xapian

You will need to install the xapian engine here if you don't already have it installed.
Install acts_as_xapian via script/plugins install http://github.com/frabcus/acts_as_xapian.git and you're good to go.  There are other forks of the plugin, and other means to install it, but this is how I did it.
You'll need to set up the  paths to your xapian databases, mine are in environment/xapian.yml

 

In your model

Include the following in any models you want indexed. 


There are several key parameters to specify here.

This tells xapian which columns to index.

Here you specify an array of arrays, in the form [column, internal identifier (must be a capital letter), prefix to use in search]. This allows you to search for matches only on a specific field, e.g. last:smith&first:dan

Note that the internal identifier must be unique across you application, and cannot be any of the reserved values ('M' & 'I' -- perhaps some others)

Again, an array of arrays, in the form [column, internal identifier (must be a number), prefix, field type]. This allows you to specify sort order in the returned values.

An optional array of associated objects to eagerly load when returning the values from your search.

 

 

In your controller

In this case, I'm searching the User model, and have formatted my query to use the prefixes I've set up above in my model.

You can also easily include pagination in your results by using a pagination plugin such as will_paginate, and passing in the pagination values via the querystring.

 

In your view

Iterate through the collection in @search.results to show the matches.
You can paginate as follows

 

Indexing your content

You will need to run the xapian rake task to populate your xapian db. Remember that after each change to the xapian settings in your model, you'll need to rebuild the index.

There it is. Quick and easy!

 

Comments

There are no comments to display.

Add a Comment

Your Comment:

Your Name:

Your Email Address: (Won't be published)

Your Website: (If you've got one)