Tuesday, July 29, 2008

Extend Thinking Sphinx to support SPH_SORT_EXPR mode

Thinking Sphinx is a Rails plugin that integrate SphinxSearch with Rails in an elegant way. Recently, I need to use SPH_SORT_EXPR mode of SphinxSearch in a Rails app but Thinking Sphinx don't support it. I think the reason why Thinking Sphinx don't support all SphinxSearch modes is that Pat Allan want to keep the plugin simple and easy to use so he leave advanced modes and configs out (some of them are SPH_SORT_EXPR mode, stopwords, wordforms, and exceptions configs).

Here is my code that extend ThinkingSphinx::Search class to support SPH_SORT_EXPR mode via :sort_expr option.

Feel free to tweak the code at RefactorMyCode.com

module ThinkingSphinx
class Search
class << self
alias_method :original_set_sort_options!, :set_sort_options!

def set_sort_options!(client, options)
expr = options[:sort_expr]
if expr.nil?
original_set_sort_options!(client, options)
client.sort_mode = :expr
client.sort_by = expr
end # class << self
end # Search
end # ThinkingSphinx

Usage: Model.search("search string", :sort_expr => "sort expression")

Find out more about my Thinking Sphinx's bug fixes and extenstions here:

No comments: