如何使用Sunspot / Solr的Rails中的特定字段搜索模型?

时间:2018-01-25 23:46:49

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

我用于太阳黑子的宝石和版本是:

  

sunspot_rails gem version 1.2.1
  rails版本2.3.18

我尝试搜索的查询和搜索方法是这样的:

query_params = { :name => 'Joe Smith',
                 :email => 'joe.smith@email.com' }

如何使用太阳黑子搜索模型,以便通过电子邮件或名称搜索,因为某些搜索可能为空(以下示例无法按预期工作)?

User.search do
   fulltext(query_params[:name], :fields => :name)
   fulltext(query_params[:email], :fields => :email)
end

*我已经重新编制了模型索引,并且字段也可以在模型中搜索*

*编辑* user.rb模型设置如下:

class User < ActiveRecord::Base 
   searchable do
      text :name
      text :email
   end
end

2 个答案:

答案 0 :(得分:0)

any_of有帮助吗?

User.search
  any_of do
    fulltext(query_params[:name], :fields => :name)
    fulltext(query_params[:email], :fields => :email)
  end
end

User.search do
  any_of do
    with(:name, query_params[:name])
    with(:email, query_params[:email])
  end
end

尝试这是因为它是一个文本字段

User.search do
  any_of do
    keywords query_params[:name], :fields => [:name]
    keywords query_params[:email], :fields => [:email]
  end
end

资源:https://github.com/sunspot/sunspot/wiki/Fulltext-search

答案 1 :(得分:0)

尝试下面的简单方法

在模型上

searchable do
    text :name
    text :email
end

在行动控制器上

@search = User.search do |searcher|
    name = [:email]
    email= [:email]

    searcher.any do
         fulltext params[:name], :fields => name
         fulltext params[:email], :fields => email
    end
end
@users = @search.results #=> carry this to view

重新索引并获得良好的结果重新启动服务器

希望有所帮助