Commit 56033c5e1c28a664d5d66b37406ea9dfd2145278
Committed by
Rodrigo Souto
1 parent
810b5519
Exists in
master
and in
12 other branches
pg_search: order results by postgresql rank
pg_search: refactor search query pg_search: Improve search test Signed-off-by: Victor Costa <vfcosta@gmail.com> Signed-off-by: Alexandre Barbosa <alexandreab@live.com>
Showing
2 changed files
with
10 additions
and
1 deletions
Show diff stats
plugins/pg_search/lib/ext/active_record.rb
... | ... | @@ -4,7 +4,8 @@ class ActiveRecord::Base |
4 | 4 | def self.pg_search_plugin_search(query) |
5 | 5 | filtered_query = query.gsub(/[\|\(\)\\\/\s\[\]'"*%&!:]/,' ').split.map{|w| w += ":*"}.join('|') |
6 | 6 | if defined?(self::SEARCHABLE_FIELDS) |
7 | - where("to_tsvector('simple', #{pg_search_plugin_fields}) @@ to_tsquery('#{filtered_query}')") | |
7 | + where("to_tsvector('simple', #{pg_search_plugin_fields}) @@ to_tsquery('#{filtered_query}')"). | |
8 | + order("ts_rank(to_tsvector('simple', #{pg_search_plugin_fields}), to_tsquery('#{filtered_query}')) DESC") | |
8 | 9 | else |
9 | 10 | raise "No searchable fields defined for #{self.name}" |
10 | 11 | end | ... | ... |
plugins/pg_search/test/unit/pg_search_plugin_test.rb
... | ... | @@ -21,6 +21,14 @@ class PgSearchPluginTest < ActiveSupport::TestCase |
21 | 21 | assert_includes search(Profile, 'admin deb'), profile2 |
22 | 22 | end |
23 | 23 | |
24 | + should 'rank profiles based on the search entry' do | |
25 | + profile1 = fast_create(Profile, :identifier => 'profile1', :name => 'debugger') | |
26 | + profile2 = fast_create(Profile, :identifier => 'profile2', :name => 'profile admin debugger') | |
27 | + profile3 = fast_create(Profile, :identifier => 'profile3', :name => 'admin debugger') | |
28 | + profile4 = fast_create(Profile, :identifier => 'profile4', :name => 'simple user') | |
29 | + assert_equal [profile2, profile3, profile1, profile4], search(Profile, 'profile admin deb') | |
30 | + end | |
31 | + | |
24 | 32 | should 'locate profile escaping special characters' do |
25 | 33 | profile = fast_create(Profile, :name => 'John', :identifier => 'waterfall') |
26 | 34 | assert_includes search(Profile, ') ( /\/\/\/\/\ o_o oOo o_o /\/\/\/\/\ ) ((tx waterfall)'), profile | ... | ... |