我正在使用Elasticsearch包装器Ruby gem Searchkick遇到一些奇怪的行为,我很乐意帮助你!
预期的行为是我应该能够搜索其中包含空格的全名。这适用于我的测试,但不适用于浏览器。
class Account
searchkick word_start: [
:first_name,
:last_name,
:name, # <======================== key line
:email,
:phone,
:company,
], callbacks: :async
def self.index_search(query:)
search(
query || '*',
fields: [
:first_name,
:last_name,
:name, # <======================== key line
:email,
:phone,
:company,
],
match: :word_start,
where: { test_account: false },
order: { created_at: :desc },
limit: 20,
misspellings: false,
)
end
def search_data
{
first_name: first_name,
last_name: last_name,
name: "#{first_name} #{last_name}", # <======================== key line
created_at: created_at,
email: email,
phone: phone,
test_account: test_account,
company: company
}
end
end
class AccountTest < ActiveSupport::TestCase
describe "::index_search" do
let(:account_0) do
FactoryGirl.create(:account, company: "Xyz Consulting") # name: "Testy McTesterson"
end
let(:account_1) do
FactoryGirl.create(:account, first_name: "Bob") # name: "Bob McTesterson"
end
let(:search) do
Account.index_search(query: query)
end
before :all do
account_0 and account_1 # instantiate
Searchkick.disable_callbacks
Account.reindex
end
describe "when there are spaces in the string" do
let(:query) { "xyz con" }
it "finds all and only the appropriate records" do
assert_equal [account_0.id], search.map(&:id)
end
end
describe "when the query matches the full name" do
let(:query) { "bob mct" }
it "finds all and only the appropriate records" do
assert_equal [account_1.id], search.map(&:id)
end
end
end
end
注意:当我从account.rb
注释掉三个“关键行”时,其中第二个测试失败了。因此,name:
方法中的#search_data
似乎正在运作。
class SearchController < ApplicationController
def index
puts "params[:query]: #{params[:query]}"
puts "custom_search.map(&:first_name): #{custom_search.map(&:first_name)}"
puts "custom_search.map(&:last_name): #{custom_search.map(&:last_name)}"
end
private
def custom_search
Account.index_search(query: params[:query])
end
end
尽管如此,在浏览器中,它似乎并没有起作用。使用上面的代码,通过浏览器搜索,我无法重现成功。
当我搜索"bob "
时,我的服务器控制台中的输出是
params[:query]: bob
custom_search.map(&:first_name): ["Bob"]
custom_search.map(&:last_name): ["McTesterdorff"]
但是一旦我搜索"bob m"
,"bob mct"
或"bob mctesterdorff"
,我就会得到空的结果(非常重要):
params[:query]: bob m
custom_search.map(&:first_name): []
custom_search.map(&:last_name): []
params[:query]: bob mct
custom_search.map(&:first_name): []
custom_search.map(&:last_name): []
params[:query]: bob mctesterdorff
custom_search.map(&:first_name): []
custom_search.map(&:last_name): []
你们都知道问题可能是什么吗?
答案 0 :(得分:0)
您需要偶尔致电Account.reindex
来索引/重新索引新项目。或者您也可以在after_commit回调中将Account.reindex
添加到相应的模型。这样,每次插入/提交后,您的新数据都将被编入索引。