Extract ES query and filter hashes into private methods in `TagSearchService` (#29288)

shrike
Matt Jankowski 2024-02-20 05:08:32 -05:00 committed by GitHub
parent 9a2b9d1484
commit 937dad1ee6
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with 29 additions and 25 deletions

View File

@ -16,7 +16,32 @@ class TagSearchService < BaseService
private private
def from_elasticsearch def from_elasticsearch
query = { definition = TagsIndex.query(elastic_search_query)
definition = definition.filter(elastic_search_filter) if @options[:exclude_unreviewed]
ensure_exact_match(definition.limit(@limit).offset(@offset).objects.compact)
rescue Faraday::ConnectionFailed, Parslet::ParseFailed
nil
end
# Since the ElasticSearch Query doesn't guarantee the exact match will be the
# first result or that it will even be returned, patch the results accordingly
def ensure_exact_match(results)
return results unless @offset.nil? || @offset.zero?
normalized_query = Tag.normalize(@query)
exact_match = results.find { |tag| tag.name.downcase == normalized_query }
exact_match ||= Tag.find_normalized(normalized_query)
unless exact_match.nil?
results.delete(exact_match)
results = [exact_match] + results
end
results
end
def elastic_search_query
{
function_score: { function_score: {
query: { query: {
multi_match: { multi_match: {
@ -50,8 +75,10 @@ class TagSearchService < BaseService
boost_mode: 'multiply', boost_mode: 'multiply',
}, },
} }
end
filter = { def elastic_search_filter
{
bool: { bool: {
should: [ should: [
{ {
@ -72,29 +99,6 @@ class TagSearchService < BaseService
], ],
}, },
} }
definition = TagsIndex.query(query)
definition = definition.filter(filter) if @options[:exclude_unreviewed]
ensure_exact_match(definition.limit(@limit).offset(@offset).objects.compact)
rescue Faraday::ConnectionFailed, Parslet::ParseFailed
nil
end
# Since the ElasticSearch Query doesn't guarantee the exact match will be the
# first result or that it will even be returned, patch the results accordingly
def ensure_exact_match(results)
return results unless @offset.nil? || @offset.zero?
normalized_query = Tag.normalize(@query)
exact_match = results.find { |tag| tag.name.downcase == normalized_query }
exact_match ||= Tag.find_normalized(normalized_query)
unless exact_match.nil?
results.delete(exact_match)
results = [exact_match] + results
end
results
end end
def from_database def from_database