Improve customer search with Full-Text index and phonetic matching

This commit is contained in:
2026-02-22 19:07:20 -05:00
parent 0197dc2a30
commit 65db8f00a8
2 changed files with 36 additions and 0 deletions

View File

@@ -181,6 +181,26 @@ class Customer < ActiveRecord::Base
end end
end end
def self.search(search)
return all if search.blank?
# 1. Clean the input: Remove existing stars and special Boolean operators
# to prevent "red**" or syntax errors from hyphens/plus signs.
clean_search = search.gsub(/[*+\-><()~]/, '')
# 2. Add a single trailing wildcard for partial matching
ft_query = "#{clean_search}*"
# 3. Use the exact column list from your migration
# Using a hybrid approach to ensure "Jonh" still finds "John"
where(
"MATCH(name, phone_number, mobile_phone_number) AGAINST(? IN BOOLEAN MODE) OR
SOUNDEX(SUBSTRING_INDEX(name, ' ', 1)) = SOUNDEX(?) OR
name LIKE ?",
ft_query, clean_search, "%#{sanitize_sql_like(clean_search)}%"
).order(Arel.sql("MATCH(name, phone_number, mobile_phone_number) AGAINST(#{connection.quote(clean_search)}) DESC"))
end
# Override the defult redmine seach method to rank results by id # Override the defult redmine seach method to rank results by id
def self.search_result_ranks_and_ids(tokens, user, project = nil, options = {}) def self.search_result_ranks_and_ids(tokens, user, project = nil, options = {})
return {} if tokens.blank? return {} if tokens.blank?

View File

@@ -0,0 +1,16 @@
#The MIT License (MIT)
#
#Copyright (c) 2016 - 2026 rick barrette
#
#Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#
#The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
class AddFullTextIndexToCustomers < ActiveRecord::Migration[7.0]
def change
# This creates a combined index for name and phone fields
add_index :customers, [:name, :phone_number, :mobile_phone_number], type: :fulltext, name: 'ft_search_idx'
end
end