Solr return type of object

153 Views Asked by At

I'm using solr for search.

In my model Client:

searchable do text :name end

And controller Client:

def index
   @search = Client.search do
     fulltext params[:search]
   end
   @clients =  @search.results
end

The in console:

cli = Client.search

=> <Sunspot::Search:{:fq=>["type:Client"], :start=>0, :rows=>30, :q=>"*:*"}> 

How to get the type of object (client)?

cli = cli.fq (undefined method `fq' for #<Sunspot::Search::StandardSearch:0xd22ab0c>)
cli = cli.type (undefined method `type' for #<Sunspot::Search::StandardSearch:0xd22ab0c>)
2

There are 2 best solutions below

0
On

I had needed this once and found no solution.

I did find a workaround that is valid, but I don't know if it is the most correct way to go:

cli = Client.search
cli.hits.first.class_name
=> "Client"
0
On

This is not really a regular use case of Sunspot, so the solution is not quite simple.

With a bit of a workaround, you can get the classes of all the types being searched for like this:

cli = Sunspot.new_search(Client)

cli.query.to_params.fetch(:fq, [])
  .first[/[^:]+\z/].gsub(/[()]|OR/, '')
  .split.map(&:constantize)

This will not trigger an actual Solr search.