我想使用ElasticSearch搜索多个参数(名称,性别,年龄)。
我到目前为止所做的是在我的模型中包含弹性搜索,并添加了as_indexed_json方法用于索引和包含关系。
require 'elasticsearch/model'
class User < ActiveRecord::Base
include Elasticsearch::Model
include Elasticsearch::Model::Callbacks
belongs_to :product
belongs_to :item
validates :product_id, :item_id, :weight, presence: true
validates :product_id, uniqueness: {scope: [:item_id] }
def as_indexed_json(options = {})
self.as_json({
only: [:id],
include: {
product: { only: [:name, :price] },
item: { only: :name },
}
})
end
def self.search(query)
# i'm sure this method is wrong I just don't know how to call them from their respective id's
__elasticsearch__.search(
query: {
filtered: {
filter: {
bool: {
must: [
{
match: {
"product.name" => query
}
}
],
must: [
{
match: {
"item.name" => query
}
}
]
}
}
}
}
)
end
end
User.import force: true
并在控制器中
def index
@category = Category.find(params[:category_id])
if params[:search].present? and params[:product_name].present?
@users = User.search(params[:product_name]).records
end
if params[:search].present? and params[:product_price].present?
@users = User.search(params[:product_price]).records
end
if params[:search].present? and params[:item].present?
if @users.present?
@users.search(item: params[:item], product: params[:product_name]).records
else
@users = User.search(params[:item]).records
end
end
端
基本上有3个用于搜索产品名称,产品价格和商品名称的输入,如果在搜索字段中只有产品名称存在,那么我正试图这样做
@users = User.search(params[:product_name]).records
这会给我记录但是如果用户在另一个搜索栏中输入另一个过滤器说产品价格或项目名称,那么它就不起作用了。任何想法或我做错的地方:/过去3天都没有出现