我在我的 rails 应用程序中添加了 elasticsearch,它工作正常。但我想让用户能够使用属性“created_at”和分数对搜索结果进行排序。我添加了一个下拉菜单来做到这一点。我的问题是我无法让它工作。我尝试了很多不同的想法,但到目前为止还没有。如果有人可以向我展示正确的方式,我将不胜感激。
搜索 Controller :
class SearchController < ApplicationController
def search
options = { sort: params[:s] }
@products = Product.search(params[:q], options).paginate(page: params[:page], per_page: 5).records
end
end
产品.rb :
require "elasticsearch/model"
class Product < ActiveRecord::Base
include Elasticsearch::Model
include Elasticsearch::Model::Callbacks
belongs_to :category
def self.search(query, options={})
@search_definition = {query: {}}
unless query.blank?
@search_definition[:query] = {
bool: {
should: [
{ multi_match: {
query: query,
fuzziness: 2,
fields: ['name^2', 'description','category.name', 'price'],
prefix_length: 2,
operator: 'and'
}}]}
}
else
@search_definition[:query] = { match_all: {} }
@search_definition[:sort] = { created_at: { order: 'desc'} }
end
if options[:sort]
@search_definition[:sort] = { options[:sort] => 'desc' }
end
__elasticsearch__.search @search_definition
end
settings analysis: {
analyzer: {
my_index_analyzer: {
type: "custom",
tokenizer: "standard",
filter: ["standard", "lowercase", "translation"]
},
my_search_analyzer: {
type: "custom",
tokenizer: "standard",
filter: ["standard", "lowercase"]
}
},
filter: {
translation: {
type: "nGram",
min_gram: 2,
max_gram: 20
}
}
}
mapping do
indexes :name, type: 'string', index_analyzer: 'my_index_analyzer', search_analyzer: 'my_search_analyzer'
indexes :description, type: 'string', index_analyzer: 'my_index_analyzer', search_analyzer: 'my_search_analyzer'
indexes :created_at, type: 'date'
indexes :category do
indexes :name, type: 'string', index_analyzer: 'my_index_analyzer', search_analyzer: 'my_search_analyzer'
end
end
def as_indexed_json(options={})
as_json(
only: [:name, :description, :price],
include: { category: { only: :name } }
)
end
end
Product.import
search.html.erb(结果页面的下拉菜单)
<div class="row">
<div class="col-xs-6 col-xs-offset-1">
<div class="btn-group pull-right">
<button class="btn btn-default btn-xs dropdown-toggle" type="button" data-toggle="dropdown">
<% sort = case
when params[:s] then params[:s]
when params[:q].blank? then 'created_at'
else 'relevancy'
end
%>
sorted by <%= sort.humanize.downcase %> <span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu">
<li><%= link_to "Sort by created at", search_path(params.except(:controller, :action).merge(s: 'created_at')), class: 'btn-xs' %></li>
<li><%= link_to "Sort by relevancy", search_path(params.except(:controller, :action).merge(s: nil)), class: 'btn-xs' %></li>
</ul>
</div>
</div>
</div>
最佳答案
Elasticsearch 排序选项接收一个数组。你可以试试这个:
@search_definition[:sort] = [{"created_at"=> { "order"=> "desc"}}]
关于ruby-on-rails - Rails 中的 Elasticsearch 排序结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32564941/