【发布时间】:2015-07-13 20:19:14
【问题描述】:
我开始在我的项目中使用 Elasticsearh,但结果排序有问题。
事实上,我需要在已连接 (belongs_to) 模型中按 hstore 记录对我的记录进行排序。
更多细节:
所以,我有一个模型,我希望它可以被搜索。该模型与其他模型有联系,代码如下:
class PropertyObject < ActiveRecord::Base
belongs_to :country, :counter_cache => true
belongs_to :region, :counter_cache => true
belongs_to :city, :counter_cache => true
belongs_to :property_object_type, :counter_cache => true
belongs_to :property_object_state, :counter_cache => true
has_one :property_object_parameter_pack, dependent: :destroy
has_one :property_object_feature_pack, dependent: :destroy
has_one :property_object_description, dependent: :destroy
has_one :property_object_seo_field, dependent: :destroy
end
我想在我的搜索结果中包含下一个字段:
模型属性对象:
- :代码:字符串
示范国家
- :title_translations :hstore
模型区域
- :title_translations :hstore
模范城市
- :title_translations :hstore
模型属性对象描述
- :title_translations :hstore
- :main_text_translations :hstore
模型 PropertyObjectParameterPack
- :价格:hstore(例如:{min => 10, max=>100})
为了完成这项工作,我创建了可搜索的关注点并将其添加到我的模型 PropertyObject 中。 这里是它的代码:
module Searchable
extend ActiveSupport::Concern
included do
include Elasticsearch::Model
include Elasticsearch::Model::Callbacks
mapping do
indexes :property_object_parameter_pack, type: 'nested' do
indexes :price do
indexes :min, type: :integer
end
end
end
# Customize the JSON serialization for Elasticsearch
def as_indexed_json(options={})
self.as_json(
include: {
country: {only: :title_translations},
region: {only: :title_translations},
city: {only: :title_translations},
property_object_description: {only: [:title_translations, :main_text_translations]},
property_object_parameter_pack: {only: [:price, :area, :rooms]}
})
end
end
end
搜索调用的控制器部分
def search
pagen = params[:page] || 1
@property_objects = PropertyObject.search(params[:q]).page(pagen).records
end
所以现在搜索工作,一切似乎都很好。但我需要按最低价格对搜索结果进行排序。
我尝试了适用于我的另一个订单的订购方法 - 但没有运气。
据我了解,我需要使用 Elasticsearch 排序来获得已经排序的结果 - 但花费大量时间尝试实现这一点并失败。
你能给我什么建议?
更新 试过这段代码:
pagen = params[:page] || 1
query = params[:q]
params[:order] ||= 'asc'
property_objects = PropertyObject.search(query) do |s|
s.query do |q|
q.string query
end
s.sort { by :property_object_parameter_pack.price.min, params[:sort]}
end
@property_objects = property_objects.page(pagen).records
有不同的变体
s.排序
- 作者:价格
- by :price.min
- by :price[:min]
- 作者:property_object_parameter_pack.price.min
- by :property_object_parameter_pack.price[:min]
而且没有运气订购。
【问题讨论】:
标签: ruby-on-rails sorting elasticsearch