Using Boolean Operators
Boolean operators allow terms to be combined through logic operators. Lucene supports AND, "+", OR, NOT and "-" as Boolean operators.
Note: Boolean operators must be ALL CAPS.
OR
The OR operator is the default conjunction operator. This means that if there is no Boolean operator between two terms, the OR operator is used. The OR operator links two terms and finds a matching document if either of the terms exist in a document. This is equivalent to a union using sets.
For example, to search for documents that contain either "apple pie" or just "orange" use the following query:
"apple pie"
OR orange
To find "apple" or "orange" use one of the following queries:
apple orange
apple
OR orange
AND
The AND operator finds documents where both terms exist anywhere in the text of a single document. This is equivalent to an intersection using sets.
For example, to search for documents that contain "apple juice" and "orange soda" use the query:
"apple juice
" AND "orange soda
"
NOT
The NOT operator excludes documents that contain the term after NOT. This is equivalent to a difference using sets.
For example, to search for documents that contain "apple juice" but not "orange soda" use the query:
"apple juice
" NOT "orange soda
"
Note: The NOT operator cannot be used with just one term.
NOT "apple juice
"
Grouping
Lucene supports using parentheses to group clauses to form sub queries. This can be very useful if you want to control the Boolean logic for a query.
To search for either "orange" or "apple" and "banana" use the query:
(orange
OR apple
) AND banana
This eliminates any confusion and makes sure that "banana" must exist and either term "orange"or "apple" may exist.