[英]Searching Multiple Terms with ElasticSearch + Tire
將Tire與Mongoid一起使用,我無法弄清楚如何構建查詢以使用ElasticSearch查找事件。 特別是,我正在嘗試查找用戶正在觀看的事件以及用戶遵循的表演者的事件:
# app/models/event.rb
class Event
include Mongoid::Document
include Tire::Model::Search
include Tire::Model::Callbacks
field :name, type: String
has_and_belongs_to_many :performers
has_many :watchers, class_name: 'User'
mapping do
indexes :name
indexes :watcher_ids, type: 'string', index: :not_analyzed
indexes :performer_ids, type: 'string', index: :not_analyzed
end
end
以下查詢僅適用於觀察者或表演者。
Tire.search 'events' do
query do
string params[:query]
# Only one of these will work at a time:
terms :performer_ids, current_user.followed_performers.collect(&:id).map(&:to_s)
terms :watcher_ids, [current_user.id.to_s]
end
end
這是一個似乎“有效”的解決方案......但感覺不對
Tire.search('events') do
query do
boolean do
should { string params[:query] }
should { string "performer_ids:#{current_user.followed_performers.collect(&:id).map(&:to_s).join(',')}" }
should { string "watcher_ids:#{current_user.id.to_s}" }
end
end
end
你正走在正確的道路上,但正如Russ Smith所建議的那樣,你需要使用filter
DSL。
現在,如果你只是反復調用filter
,你將執行一個聯合: AND
。 如果你想返回兩個事件用戶觀看或表演者的用戶跟隨,你必須使用一個or
過濾器。
此外,為了獲得最佳性能,請使用filtered
查詢,而不是頂級篩選器 - 在前一種情況下,首先運行篩選器,切割語料庫並僅對此子集執行查詢。
代碼應該如下所示:
Tire.search 'events' do
query do
filtered do
query do
string params[:query]
end
filter :or, terms: { organization_ids: current_user.followed_performers.collect(&:id).map(&:to_s) },
terms: { watcher_ids: [current_user.id.to_s] }
end
end
end
有關更多示例,請參閱集成測試:
我認為你要找的是一個過濾器。 這不是經過完全測試的代碼,但它可能會引導您朝着正確的方向前進。
class Event
include Mongoid::Document
include Tire::Model::Search
include Tire::Model::Callbacks
field :name, type: String
has_and_belongs_to_many :performers
has_many :watchers, class_name: 'User'
mapping do
indexes :name
indexes :watcher_ids, type: 'integer', index: :not_analyzed
indexes :performer_ids, type: 'integer', index: :not_analyzed
end
end
Tire.search('events') do
query do
string 'my event'
end
filter :in, :organization_ids, [1,2,3]
filter :in, :watcher_ids, [1]
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.