开发者

Sunspot `LIKE` query

开发者 https://www.devze.com 2023-03-05 03:40 出处:网络
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|

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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消