1
votes

The gem and version I am using for sunspot is:

sunspot_rails gem version 1.2.1
rails version 2.3.18

The query I am trying to search with and search method is something like this:

query_params = { :name => 'Joe Smith',
                 :email => '[email protected]' }

How can I search a model with sunspot so that it searches via email or just name, since one can be blank for some searches (the below example did not work as expected)?

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

* I have reindexed the models and the fields are all searchable within the model as well *

* EDIT * The user.rb model is set up like this:

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

2 Answers

0
votes

Try the simple way like below

On the model

searchable do
    text :name
    text :email
end

On the controller of action

@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

reindex and for good results restart the server

Hope it helps

0
votes

Does any_of help?

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

or

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

Try this due to it being a text field

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

Resource: https://github.com/sunspot/sunspot/wiki/Fulltext-search