From a85eeffd95a4b85d7ca9b870a4ea162a8f61e7c2 Mon Sep 17 00:00:00 2001 From: Victor Costa Date: Tue, 17 Nov 2015 10:57:10 -0300 Subject: [PATCH] pg_search: order results by postgresql rank --- plugins/pg_search/lib/ext/active_record.rb | 4 +++- plugins/pg_search/test/unit/pg_search_plugin_test.rb | 7 +++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/plugins/pg_search/lib/ext/active_record.rb b/plugins/pg_search/lib/ext/active_record.rb index 6b8712d..13de478 100644 --- a/plugins/pg_search/lib/ext/active_record.rb +++ b/plugins/pg_search/lib/ext/active_record.rb @@ -4,7 +4,9 @@ class ActiveRecord::Base def self.pg_search_plugin_search(query) filtered_query = query.gsub(/[\|\(\)\\\/\s\[\]'"*%&!:]/,' ').split.map{|w| w += ":*"}.join('|') if defined?(self::SEARCHABLE_FIELDS) - where("to_tsvector('simple', #{pg_search_plugin_fields}) @@ to_tsquery('#{filtered_query}')") + select("*,ts_rank(to_tsvector('simple', #{pg_search_plugin_fields}), to_tsquery('#{filtered_query}')) as rank"). + where("to_tsvector('simple', #{pg_search_plugin_fields}) @@ to_tsquery('#{filtered_query}')"). + order("rank DESC") else raise "No searchable fields defined for #{self.name}" end diff --git a/plugins/pg_search/test/unit/pg_search_plugin_test.rb b/plugins/pg_search/test/unit/pg_search_plugin_test.rb index 6069f37..ee9f980 100644 --- a/plugins/pg_search/test/unit/pg_search_plugin_test.rb +++ b/plugins/pg_search/test/unit/pg_search_plugin_test.rb @@ -21,6 +21,13 @@ class PgSearchPluginTest < ActiveSupport::TestCase assert_includes search(Profile, 'admin deb'), profile2 end + should 'rank profiles based on the search entry' do + profile1 = fast_create(Profile, :identifier => 'profile1', :name => 'debugger') + profile2 = fast_create(Profile, :identifier => 'profile2', :name => 'profile admin debugger') + profile3 = fast_create(Profile, :identifier => 'profile3', :name => 'admin debugger') + assert_equal [profile2, profile3, profile1], search(Profile, 'profile admin deb') + end + should 'locate profile escaping special characters' do profile = fast_create(Profile, :name => 'John', :identifier => 'waterfall') assert_includes search(Profile, ') ( /\/\/\/\/\ o_o oOo o_o /\/\/\/\/\ ) ((tx waterfall)'), profile -- libgit2 0.21.2