【问题标题】:Search for empty string field in Sunspot (Solr)在 Sunspot (Solr) 中搜索空字符串字段
【发布时间】:2014-05-01 16:02:31
【问题描述】:

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

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

我试图搜索的特定对象有一个 :middle_name 属性,其中包含 ''、一个空字符串并且属于 String 数据类型。根据该信息,我假设 Sunspot 还在 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 之类的查询的信息,它们都返回一个空集:[]

任何人都知道一种实际可行的方法和/或最好的方法是什么?

【问题讨论】:

  • 使用Utils.escape 使上面的代码工作。

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


【解决方案1】:

为了让它工作,你有 make monkey patch 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 服务器。

【讨论】:

  • 我特别使用了这个:pastebin.com/nwRFMwX6。我没有花时间去真正思考它的作用,但它确实有效。
  • 它为 #<:query::restriction::equalto:0x007fb5114bdb88> 提供“未定义的方法 `escape'”
【解决方案2】:

试试这个:

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'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-10
    • 2012-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-27
    相关资源
    最近更新 更多