Sunspot `LIKE` query

五迷三道 提交于 2019-12-01 09:36:05

问题


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:


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.



来源:https://stackoverflow.com/questions/5943254/sunspot-like-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!