Tristate
Tristate

Reputation: 1831

How to create an empty lucene query

For my Lucene Queries I have some preconditions for security reasons.

if isValid()
 return build.parse query
else
 return null

I want to replace this return null. I need something like "empty" query, a query thats will nothing do.

Is there a way to build it ?

Upvotes: 1

Views: 361

Answers (2)

Ben Borchard
Ben Borchard

Reputation: 641

If you just want a query that won't match any documents you should use MatchNoDocsQuery

Upvotes: 3

andrewJames
andrewJames

Reputation: 22057

You can take advantage of the "prohibit" operator (-) for this.

For example:

-anything

...where the literal text "anything" is used - but you can use any literal text you like, here. It could be apples or a term which actually does exist in your index.

If you have a default field defined, this will be executed against that default field.

Or you can specify a field in your documents:

-body:anything

Additional Notes

How does this work? Why does -anything not return any results? Why doesn't it find all results which do not contain the term "anything"?

First, -anything forces all documents which do contain anything to have a score of zero (they are prohibited). But after that has been executed, there are no more clauses in the query. There is no more information for Lucene to use, to determine how any remaining documents should be scored. Therefore all documents remain unscored (they are all effectively 0).

Documents with no score are never returned by a standard query.

The "prohibit" operator is typically used in conjunction with one or more additional query clauses. Here we are using it on its own, which is how we can exploit this behavior.

(You can also use NOT as a synonym for -.)

Upvotes: 1

Related Questions