Lucene Query Syntax

Lucene has a custom query syntax for querying its indexes.

I can do no better than point you to the official docs: http://lucene.apache.org/java/3_5_0/queryparsersyntax.html

The query syntax has not changed significantly since Lucene 1.3 (it is now 3.5.0).

Parsing Queries

Queries can be parsed by constructing a QueryParser object and invoking the parse() method.

String querystr = args.length > 0 ? args[0] : "lucene";
Query q = new QueryParser(Version.LUCENE_CURRENT, "title", analyzer).parse(querystr);

Programmatic construction of queries

Lucene queries can also be constructed programmatically. This can be really handy at times. Besides, there are some queries which are not possible to construct by parsing.

Available query objects as of 3.4.0 are:

Use the BooleanQuery object to join and nest queries.

These classes are part of the org.apache.lucene.search package.

Here's a simple example:

String str = "foo bar";
String id = "123456";
BooleanQuery bq = new BooleanQuery();
Query query = qp.parse(str);
bq.add(query, BooleanClause.Occur.MUST);
bq.add(new TermQuery(new Term("id", id), BooleanClause.Occur.MUST_NOT);

blog comments powered by Disqus