Xapian search – acts_as_xapian tip

We use xapian as our offline indexing solution here at ProjectX. Recently, Francis Irving from mySociety has started a fantastic Rails plugin, acts_as_xapian. I’ll leave the introductions to the aforementioned pages. Suffice to say that it is quite easy to install, and it utilizes all the power of Xapian in a very smooth way.

One thing I have not been able to crack is to utilize association proxies on searches. Locomotivation has a solution using named_scope, but that approach removes all ordering, in addition to issuing one more unnecessary SQL statement.

class Lesson < ActiveRecord::Base
    named_scope :find_with_xapian, lambda { |*args| {:conditions => ["lessons.id in (?)", ActsAsXapian::Search.new([Lesson], args.to_s).results.collect{|x| x[:model].id}]}}
end

But if we do this instead, we can now do association proxies

class Lesson < ActiveRecord::Base
    def self.find_with_xapian(search_term, options={})
      ActsAsXapian::Search.new([self], search_term, options).results.collect{|x| x[:model]}
    end
end

current_user.lessons.find_with_xapian "something"

That would automatically scope and return lessons that belong to the current user only. Awesome!

Update: The code is not showing quite as nicely. I have pasted the same code in Pastie – http://pastie.org/270114

One Comment

  1. [...] to my first post on using acts_as_xapian, I have been trying to make xapian work with pagination and association proxies [...]