From 937dad1ee6cfe333435709dc1c88655ffc2614b1 Mon Sep 17 00:00:00 2001 From: Matt Jankowski Date: Tue, 20 Feb 2024 05:08:32 -0500 Subject: [PATCH] Extract ES query and filter hashes into private methods in `TagSearchService` (#29288) --- app/services/tag_search_service.rb | 54 ++++++++++++++++-------------- 1 file changed, 29 insertions(+), 25 deletions(-) diff --git a/app/services/tag_search_service.rb b/app/services/tag_search_service.rb index d5d1974275..929cfd884f 100644 --- a/app/services/tag_search_service.rb +++ b/app/services/tag_search_service.rb @@ -16,7 +16,32 @@ class TagSearchService < BaseService private 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: { query: { multi_match: { @@ -50,8 +75,10 @@ class TagSearchService < BaseService boost_mode: 'multiply', }, } + end - filter = { + def elastic_search_filter + { bool: { 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 def from_database