Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Use trigram search (if available) when searching by product name (#12787)

Damian Kaczmarczyke349807c3458
diff --git a/core/app/models/concerns/spree/product_scopes.rb b/core/app/models/concerns/spree/product_scopes.rb
index b145a35922..c42c3dd79e 100644
--- a/core/app/models/concerns/spree/product_scopes.rb
+++ b/core/app/models/concerns/spree/product_scopes.rb
@@ -305,7 +305,17 @@ module Spree
# .search_by_name
if defined?(PgSearch)
include PgSearch::Model
- pg_search_scope :search_by_name, against: { name: 'A', meta_title: 'B' }, using: { tsearch: { any_word: true, prefix: true } }
+
+ begin
+ if ActiveRecord::Base.connection.extension_enabled?('pg_trgm')
+ pg_search_scope :search_by_name, against: { name: 'A', meta_title: 'B' }, using: { trigram: { threshold: 0.3, word_similarity: true } }
+ else
+ pg_search_scope :search_by_name, against: { name: 'A', meta_title: 'B' }, using: { tsearch: { any_word: true, prefix: true } }
+ end
+ rescue ActiveRecord::ConnectionNotEstablished, PG::Error => e
+ Rails.logger.warn("Could not check pg_trgm extension, falling back to tsearch for product search: #{e.message}")
+ pg_search_scope :search_by_name, against: { name: 'A', meta_title: 'B' }, using: { tsearch: { any_word: true, prefix: true } }
+ end
else
def self.search_by_name(query)
i18n { name.lower.matches("%#{query.downcase}%") }
diff --git a/core/app/models/spree/product.rb b/core/app/models/spree/product.rb
index 12fed71da1..6de47253ad 100644
--- a/core/app/models/spree/product.rb
+++ b/core/app/models/spree/product.rb
@@ -50,8 +50,16 @@ module Spree
if defined?(PgSearch)
include PgSearch::Model
- pg_search_scope :search_by_name, against: { name: 'A', meta_title: 'B' },
- using: { tsearch: { prefix: true, any_word: true } }
+ begin
+ if ActiveRecord::Base.connection.extension_enabled?('pg_trgm')
+ pg_search_scope :search_by_name, against: { name: 'A', meta_title: 'B' }, using: { trigram: { threshold: 0.3, word_similarity: true } }
+ else
+ pg_search_scope :search_by_name, against: { name: 'A', meta_title: 'B' }, using: { tsearch: { any_word: true, prefix: true } }
+ end
+ rescue ActiveRecord::ConnectionNotEstablished, PG::Error => e
+ Rails.logger.warn("Could not check pg_trgm extension, falling back to tsearch for product search: #{e.message}")
+ pg_search_scope :search_by_name, against: { name: 'A', meta_title: 'B' }, using: { tsearch: { any_word: true, prefix: true } }
+ end
end
before_save :set_slug