Sunspot `LIKE` query

2019-02-19 11:24发布

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?

1条回答
女痞
2楼-- · 2019-02-19 11:35

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.

查看更多
登录 后发表回答