在Sunspot(Solr)中搜索空字符串字段

时间:2014-05-01 16:02:31

标签: ruby-on-rails ruby sunspot sunspot-rails sunspot-solr

在我的模型中,我只是使用类似的东西:

class Person < ActiveRecord::Base
  searchable do
    string :middle_name
  end
end

我正在尝试搜索的特定对象有一个:middle_name属性,其中包含'',一个空字符串,并且是String数据类型。基于该信息,我假设太阳黑子也在Solr索引中为该字段保存一个空字符串。

成功执行Person.reindexSunspot.commit后,我尝试在rails控制台中使用Person.search{with(:middle_name, '')}.results搜索所述对象,并​​在Solr查询语法方面返回400错误。

然后我环顾四周,找到了有关Person.search{with(:middle_name, "* TO ''")}.resultsPerson.search{without(:middle_name, "* TO *")}.results等查询的一些信息,这两个信息都返回一个空集:[]

任何人都知道实际运作的方式和/或最佳方法是什么?

2 个答案:

答案 0 :(得分:0)

试试这个:

person = Person.solr_search do
           keywords params[:middle_name] 
         end

person.results

If you want to try in console then, replace params[:middle_name] 
with middle name of your choice. eg 'burger'

答案 1 :(得分:0)

为了使它工作,你已经制作了猴子补丁Sunspot::Query::Restriction::EqualTo方法。在config / initializers目录中创建一个新文件并添加以下代码:

module Sunspot
    module Query
      module Restriction

          class EqualTo < Base
              def to_positive_boolean_phrase
                  case @value
                  when nil
                     "#{escape(@field.indexed_name)}:[* TO *]"
                  when ''
                     %Q(#{escape(@field.indexed_name)}:[* TO ""])
                  else
                     super
                  end
               end

               def negated?
                  if @value.nil?
                      !super
                  else
                      super
                  end
               end

               private

               def to_solr_conditional
                   "#{solr_value}"
               end

           end
       end
    end
end

请记住在尝试之前重启rails服务器。