我正在使用Tire gem在我的应用程序中执行搜索。在我的控制器中,我执行搜索:
@results = Model.search(query: params[:query])然后,我希望使用自定义排序方法对结果进行重新排序
@results.each_with_hit do |result|
# complex math that computes final score.
# calculations include model attributes and _score field
# ...
# modify score for the result
result[1]["_score"] = final_score
end我尝试使用新分数对结果进行排序,方法是:
@results.each_with_hit.sort_by {|r| r[1][_score]}但它似乎不起作用。
发布于 2013-06-09 23:48:37
我假设您了解custom_score查询,并且有一些排除使用它的特定要求。请注意,您可以在脚本中访问文档属性(请参阅链接集成测试),因此值得深入研究。
如果您真的想重新排序查询返回的有限结果(因此可能会导致计算不正确),那么Enumerable#sort_by方法确实应该可以很好地工作:
require 'tire'
Tire.index 'articles' do
delete
create
store title: 'One', views: 10
store title: 'Two', views: 30
store title: 'Three', views: 20
store title: 'Four', views: 10
refresh
end
s = Tire.search('articles') { query { string 'title:T*' } }
s.results.
# Sort by sum of title length and views
#
sort_by do |d|
d.title.size + d.views
end.
# Sort in descending order
#
reverse.
# Print results
#
each do |d|
puts "* #{d.title} (#{d.title.size + d.views})"
end它对普通文档的工作方式应该与对模型的工作方式相同。
https://stackoverflow.com/questions/17001699
复制相似问题