Nov 17, 2012

Enable wildcard searches in Sunspot 2.0

We've got a web application that allows folks to search for heavy equipment by part numbers. Sometimes those part numbers follow patterns which makes doing a partial search worthwhile. But we didn't want to clutter the searches by default. So if somebody searched for 10332 we and it wasn't an exact match we'd skip returning any results but 10332* should return anything that was close.


In Solr/Sunspot the default query mode is Dismax. It's fine for the job but there's no easy support for wildcard searches. It is possible to modify the solr/schema.config file but that won't necessarily be effective if you're using a hosted solr solution.

The solution isn't ideal, but thanks to jashkenas I found something which does the trick.

First create a file in config/initializers called solr_edismax.rb or something similar. We'll monkey patch solr to force it to use the Edismax query mode which provides wildcard searches. I'm hoping in the future that this will be the default...

Then, paste in this code snippet.


OriginalDismax = Sunspot::Query::Dismax

class PatchedDismax < OriginalDismax

  def to_params
    params = super
    params[:defType] = 'edismax'
    params
  end

  def to_subquery
    query = super
    query = query.sub '{!dismax', '{!edismax'
    query
  end

end

Sunspot::Query.send :remove_const, :Dismax
Sunspot::Query::Dismax = PatchedDismax



Once done, your query parameters sent to solr via sunspot should use defType=edismax by default. The adjust_solr_params and adjust_query_params methods didn't seem to work at the time of this writing, but if that changes, those would also be valid ways to accomplish this.

No comments:

Post a Comment