Ruby on rails 更复杂的搜索结果排序-轮胎
我正在使用Tire gem在我的应用程序中执行搜索。在我的控制器中,我执行搜索:Ruby on rails 更复杂的搜索结果排序-轮胎,ruby-on-rails,elasticsearch,tire,Ruby On Rails,elasticsearch,Tire,我正在使用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
@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]}
但是它似乎不起作用。我假设您知道这个查询,并且您有一些特定的要求,这些要求排除了使用它的可能性。请注意,您可以访问脚本中的文档属性(请参阅链接集成测试),因此值得深入研究 如果您真的想使用查询返回的有限结果(从而可能导致计算不正确),那么
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
它对普通文档的工作方式应该与对模型的工作方式相同。我面临的问题是,一旦我这样做,我就失去了在视图中对结果分页的能力。我想对
Tire::results::Collection
类中的结果数组进行排序我可以访问custom\u score
方法中搜索的max\u score
值吗?