Browse Source

Return `MatchNoDocsQuery` if query string is emtpy

Closes #3952
Simon Willnauer 11 years ago
parent
commit
f0bce08c30

+ 6 - 0
docs/reference/query-dsl/queries/query-string-syntax.asciidoc

@@ -287,3 +287,9 @@ query as a search for `"wi OR fi"`, while the token stored in your
 index is actually `"wifi"`.  Escaping the space will protect it from
 being touched by the query string parser: `"wi\ fi"`.
 ****
+
+===== Empty Query
+
+If the query string is empty or only contains whitespaces the
+query string is interpreted as a `no_docs_query` and will yield
+an empty result set. 

+ 11 - 0
src/main/java/org/apache/lucene/queryparser/classic/MapperQueryParser.java

@@ -28,6 +28,7 @@ import org.apache.lucene.index.Term;
 import org.apache.lucene.search.*;
 import org.apache.lucene.util.automaton.RegExp;
 import org.elasticsearch.common.lucene.Lucene;
+import org.elasticsearch.common.lucene.search.MatchNoDocsQuery;
 import org.elasticsearch.common.lucene.search.Queries;
 import org.elasticsearch.common.lucene.search.XFilteredQuery;
 import org.elasticsearch.common.unit.Fuzziness;
@@ -870,4 +871,14 @@ public class MapperQueryParser extends QueryParser {
         }
         return fields;
     }
+
+    public Query parse(String query) throws ParseException {
+        if (query.trim().isEmpty()) {
+            // if the query string is empty we return no docs / empty result
+            // the behavior is simple to change in the client if all docs is required
+            // or a default query
+            return new MatchNoDocsQuery();
+        }
+        return super.parse(query);
+    }
 }

+ 9 - 1
src/test/java/org/elasticsearch/search/query/SimpleQueryTests.java

@@ -90,7 +90,15 @@ public class SimpleQueryTests extends ElasticsearchIntegrationTest {
         assertThat(hits[0].score(), allOf(greaterThan(hits[1].getScore()), greaterThan(hits[2].getScore())));
 
     }
-
+    @Test // see #3952
+    public void testEmptyQueryString() throws ExecutionException, InterruptedException, IOException {
+        createIndex("test");
+        indexRandom(true, client().prepareIndex("test", "type1", "1").setSource("field1", "the quick brown fox jumps"),
+                client().prepareIndex("test", "type1", "2").setSource("field1", "quick brown"),
+                client().prepareIndex("test", "type1", "3").setSource("field1", "quick"));
+        assertHitCount(client().prepareSearch().setQuery(queryString("quick")).get(), 3l);
+        assertHitCount(client().prepareSearch().setQuery(queryString("")).get(), 0l); // return no docs
+    }
 
     @Test // see https://github.com/elasticsearch/elasticsearch/issues/3177
     public void testIssue3177() {