正如 David 所建议的那样,您可以将bool 查询与minimum_number_should_match
.
但这里有一些关于查询字符串中通配符的想法。
在您的情况下,前缀查询比查询字符串更可取:
- 查询字符串中的通配符比前缀查询慢
- 您
*
在用户提供的查询末尾手动添加 - 明确指示您要使用前缀查询(专为此而设计)
在轮胎中,这是一个完整的例子:
require 'tire'
class Car
include Tire::Model::Persistence
property :name, type: "multi_field",
fields: {
name: { type: 'string', analyzer: 'snowball' },
exact: { type: 'string', index: 'not_analyzed' }
}
end
Car.index.delete
Car.create_elasticsearch_index
Car.create name: 'Alfa'
Car.create name: 'Alfa Romeo'
Car.index.refresh
queries = [ 'Alfa', 'Alf', 'Alfa Remeo', 'Remeo' ] # Notice the spelling mistake
puts "Searching for: #{queries.join(', ')}", "="*80, ""
queries.each do |q|
s = Car.search do
query do
boolean minimum_number_should_match: 1 do
should { prefix 'name', q }
should { prefix 'name.exact', q, boost: 10 }
should { match :name, q, operator: 'AND', fuzziness: 0.4 }
end
end
end
puts "Found #{s.results.size} results for query '#{q}':",
"-"*80,
s.map { |d| "#{d.name} (score: #{d._score})" }.join(", "),
""
end
结果:
Searching for: Alfa, Alf, Alfa Remeo, Remeo
================================================================================
Found 2 results for query 'Alfa':
--------------------------------------------------------------------------------
Alfa (score: 0.67262733), Alfa Romeo (score: 0.67027444)
Found 2 results for query 'Alf':
--------------------------------------------------------------------------------
Alfa (score: 0.6693944), Alfa Romeo (score: 0.66834825)
Found 1 results for query 'Alfa Remeo':
--------------------------------------------------------------------------------
Alfa Romeo (score: 0.08865173)
Found 1 results for query 'Remeo':
--------------------------------------------------------------------------------
Alfa Romeo (score: 0.06392767)