From e53b4bfba625b8d529759cf4fad42998c24e8286 Mon Sep 17 00:00:00 2001 From: Mat Brown Date: Wed, 14 Jul 2010 18:14:00 -0400 Subject: [PATCH] Properly (if convolutedly) query for empty strings [#112 state:resolved] --- sunspot/lib/sunspot/query/restriction.rb | 9 ++++--- sunspot/spec/api/query/scope_examples.rb | 7 ++++++ .../spec/integration/scoped_search_spec.rb | 25 +++++++++++++++++++ 3 files changed, 38 insertions(+), 3 deletions(-) diff --git a/sunspot/lib/sunspot/query/restriction.rb b/sunspot/lib/sunspot/query/restriction.rb index 02cdbf3ed..aa75b2e22 100644 --- a/sunspot/lib/sunspot/query/restriction.rb +++ b/sunspot/lib/sunspot/query/restriction.rb @@ -149,10 +149,13 @@ def solr_value(value = @value) # class EqualTo < Base def to_positive_boolean_phrase - unless @value.nil? - super - else + case @value + when nil "#{escape(@field.indexed_name)}:[* TO *]" + when '' + %Q(#{escape(@field.indexed_name)}:[* TO ""]) + else + super end end diff --git a/sunspot/spec/api/query/scope_examples.rb b/sunspot/spec/api/query/scope_examples.rb index 2194c68fb..2f6c8526d 100644 --- a/sunspot/spec/api/query/scope_examples.rb +++ b/sunspot/spec/api/query/scope_examples.rb @@ -13,6 +13,13 @@ connection.should have_last_search_including(:fq, 'title_ss:"OR"') end + it 'scopes by exact match with empty string' do + search do + with :title, '' + end + connection.should have_last_search_including(:fq, 'title_ss:[* TO ""]') + end + it 'scopes by exact match with time' do time = Time.parse('1983-07-08 05:00:00 -0400') search do diff --git a/sunspot/spec/integration/scoped_search_spec.rb b/sunspot/spec/integration/scoped_search_spec.rb index 3efa299b4..f5afae0e1 100644 --- a/sunspot/spec/integration/scoped_search_spec.rb +++ b/sunspot/spec/integration/scoped_search_spec.rb @@ -144,6 +144,31 @@ def self.test_field_type(name, attribute, field, *values) end end + describe 'empty strings' do + before :all do + Sunspot.remove_all + @posts = [Post.new(:title => ''), Post.new(:title => 'Bogus'), Post.new] + Sunspot.index!(@posts) + end + + it 'should filter results with an empty string' do + search = Sunspot.search(Post) { with(:title, '') } + search.results.should == [@posts[0]] + end + + it 'should not exclude results with non-empty string value' do + Sunspot.search(Post) { without(:title, '') }.results.should include(@posts[1]) + end + + it 'should not exclude results with no value' do + Sunspot.search(Post) { without(:title, '') }.results.should include(@posts[2]) + end + + it 'should exclude results with empty string value' do + Sunspot.search(Post) { without(:title, '') }.results.should_not include(@posts[0]) + end + end + describe 'prefix searching' do before :each do Sunspot.remove_all