How can I search on list of values using Lucene Query interface

full-text-search, lucene, search

Solution

Combining queries togetheer with a `BooleanQuery` is the correct way to reproduce a query like `ID:(1 OR 2 OR 3)`. The query parser will generate a BooleanQuery similar to what you provided for that syntax, so you are absolutely doing the right thing here.

You might be able to make use of `PrefixQuery`, `NumericRangeQuery` or `TermRangeQuery` to simplify matters, if they actually suit your needs in practice, but there is nothing wrong with what you are doing already.

Problem

Simplistic Problem description: Lucene index has two fields per document: ID and NAME. I want to make a query using the Lucene Query interface such that I can find all the documents where ID is 1 OR 2 OR 3 OR so on. The IDs to be searched will be in a list and can potentially have upto 30 elements. If I was using the query parser I would have done something like ``` ID:(1 OR 2 OR 3) ``` But the application is already heavily committed to the Query interface and I want to follow the current pattern. Only way I can think of doing this with Query interface is create n term queries and group them using the Boolean query as below ``` BooleanQuery booleanQuery = new BooleanQuery(); (String searchId : lstIds) { booleanQuery.add(new TermQuery(new Term("ID", searchId)), BooleanClause.Occur.SHOULD); } ``` But is there a better/more efficient way of doing this?

Original source