How can I query for terms in a collection using Lucene.Net, similar to the SQL IN statement?
We are trying to find if documents have a specific field value in the set of possible values,
field:[value1, value2, value3, ..., valueN]
which will return an element if it matches any of the input values, similar to the SQL statement IN()
.
It will look like a query range
, but the elements do not necessarily describe the range.
An example of using the Lucene.Net API would be
var query = new QueryParser(version, "FieldName", analyzer).In("value1", "value2", "value3");
Is this possible in Lucene.Net?
source to share
field:value1 field:value2 ....
must do the trick. By default, all OR
ed members .
Programmatically, you can try,
public static Query In(string fieldName, IEnumerable<string> values)
{
var query = new BooleanQuery();
foreach (var val in values)
{
query.Add(new TermQuery(new Lucene.Net.Index.Term(fieldName, val)), BooleanClause.Occur.SHOULD);
}
return query;
}
source to share
As @ I4V pointed out, it defaults to Lucene conditions OR
, so this should give you the output you want,
public Query In(string propertyName, IEnumerable<string> collection)
{
var query = new QueryParser(version, propertyName, analyzer).Parse(string.Join(" ", collection));
return query;
}
based,
field:value1, value2, value3, ..., valueN
will return any document with at least one value in the collection.
source to share