Return `MatchNoDocsQuery` if query string is emtpy

Closes #3952
This commit is contained in:
Simon Willnauer 2014-01-20 12:46:04 +01:00
parent c8d661608c
commit f0bce08c30
3 changed files with 26 additions and 1 deletions

View File

@ -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 index is actually `"wifi"`. Escaping the space will protect it from
being touched by the query string parser: `"wi\ fi"`. 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.

View File

@ -28,6 +28,7 @@ import org.apache.lucene.index.Term;
import org.apache.lucene.search.*; import org.apache.lucene.search.*;
import org.apache.lucene.util.automaton.RegExp; import org.apache.lucene.util.automaton.RegExp;
import org.elasticsearch.common.lucene.Lucene; 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.Queries;
import org.elasticsearch.common.lucene.search.XFilteredQuery; import org.elasticsearch.common.lucene.search.XFilteredQuery;
import org.elasticsearch.common.unit.Fuzziness; import org.elasticsearch.common.unit.Fuzziness;
@ -870,4 +871,14 @@ public class MapperQueryParser extends QueryParser {
} }
return fields; 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);
}
} }

View File

@ -90,7 +90,15 @@ public class SimpleQueryTests extends ElasticsearchIntegrationTest {
assertThat(hits[0].score(), allOf(greaterThan(hits[1].getScore()), greaterThan(hits[2].getScore()))); 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 @Test // see https://github.com/elasticsearch/elasticsearch/issues/3177
public void testIssue3177() { public void testIssue3177() {