2

I'm using sunspot. How can I run a LIKE query (LIKE %q%)? I would like to do something like this:

 @search = Sunspot.search(User) do |q|
   q.text_fields { with(:company_name).like(params[:q]) }
 end.results

instead of:

@search = Sunspot.search(User) do |q|
  q.text_fields { with(:company_name).starting_with(params[:q]) }
end.results

which partially works for me. Reviewing the sunspot code, I found this piece of code:

class StartingWith < Base
  private

  def to_solr_conditional
    "#{solr_value(@value)}*"
  end
end

It basically generates the following sunspot search hash:

Sunspot.search(User) do |q| 
  q.text_fields { with(:company_name).starting_with("sta")} }
end

=> Sunspot::Search:{:q=>"*:*", :fq=>["type:User", "company_name_text:sta*"]} 

In case there's no simpler way of implementing LIKE %query%, how should I create a new class Like with the method to_solr_conditional which generates the SOLR logic?

javanna
  • 59,145
  • 14
  • 144
  • 125
jpemberthy
  • 7,473
  • 8
  • 44
  • 52
  • What do you mean by 'partially works for me'? :) In fact, the problem is that the search does not work, or you just want a method alias? – Vlad Zloteanu May 18 '11 at 17:07
  • Also, what do you mean by 'no simpler way'? What can it be more simple than .starting_with('sta') ? – Vlad Zloteanu May 18 '11 at 17:14
  • Hey Vlad, thanks for your answer, I'll explain in the following gist why it does partially work for me. https://gist.github.com/8257e7c4e512aa8a45df thanks! – jpemberthy May 18 '11 at 18:43

1 Answers1

3

If you use the standard DisMax handler, it does not support wildcards. You have 2 options:

a. Activate EdgeNGramFilter:

<fieldType name="text" class="solr.TextField" omitNorms="false">
  <analyzer type="index">
    ..
    <filter class="solr.EdgeNGramFilterFactory" minGramSize="2" maxGramSize="15" side="front"/>
    ..
  </analyzer>
</fieldType>

b. Use nightly build Solr with EDismax Handler.

See wiki article on sunspot docs or similar question on SO.

Community
  • 1
  • 1
Vlad Zloteanu
  • 8,464
  • 3
  • 41
  • 58