开发者

Sunspot Rails to order search results by model id?

Assume that I have the following model and I have made it searchable with sunspot_rails.

class Case < ActiveRecord::Base
  searchable do
  end
end

Standard schema.xml of Sunspot in Rails declare id as an indexed field. When I use the web interface to access solr and test queries a query like:

http://localhost:8982/solr/select/?q=id%3A%22Case+15%22&version=2.2&start=0&rows=10&indent=on

which searches for Cases with id equal to Case 15 works fine and returns results.

The problem is when I carry out the search with Sunspot Rails in the rails console:

s = Case.search do 
    keywords('id:"Case 15"')
end

I get:

=> <Sunspot::Search:{:fl=>"* score", :rows=>10, :start=>0, :q="id:\"Case 15\"", :defType=>"dismax", :fq=>["type:Case"]}>

which show that it correctly puts in :q the correct query value, but the hits are 0:

s.hits

returns

=> []

If we assume that keywords is not equivalent and only searches the text field (full-text search) and not the field defined before the colon :, then I can try the following:

s = Case.search do
  w开发者_如何学运维ith(:id, "Case 15")
end

but this fails with a Sunspot exception:

Sunspot::UnrecognizedFieldError: No field configured for Case with name 'id'

How can I search using the indexed standard solr/sunspot id field of my model?

And to make the question more useful, how can I order by the id. The following does not work:

s = Case.search do
  keywords("xxxx")
  order_by :id, :desc
end

does not work. Sunspot::UnrecognizedFieldError: No field configured for Case with name 'id'


The id that you are talking about is a Sunspot internal field and it should not be used directly.

Why not add your own id field (change variable name, to avoid name collision):

class Case < ActiveRecord::Base
  searchable do
    integer :model_id {|content| content.id }
  end
end

and then

s = Case.search do
  keywords("xxxx")
  order_by :model_id, :desc
end

Other (messy) option would be to hack directly solr params:

s = Case.search do
  keywords("xxxx")
  adjust_solr_params(:sort, 'id desc')
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜