How to query for terms IN a collection using Lucene.Net, similar to SQL's IN operator?

纵然是瞬间 提交于 2019-11-28 05:15:27

问题


We are trying to search whether documents have a particular field value in a collection of possible values,

field:[value1, value2, value3, ..., valueN]

which would return the element if it matches any of the input values, similar to SQL's IN() operator.

This would be similar to a range query, but the elements do not necessarily describe a range.

An example using Lucene.Net API would be,

var query = new QueryParser(version, "FieldName", analyzer).In("value1", "value2", "value3");

Is this possible in Lucene.Net?


回答1:


field:value1 field:value2 .... should do the trick. By default all terms are ORed.

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;
}



回答2:


As @I4V mentioned, Lucene ORs terms by default, so this should give you the wanted result,

public Query In(string propertyName, IEnumerable<string> collection)
{
    var query = new QueryParser(version, propertyName, analyzer).Parse(string.Join(" ", collection));

    return query;
}

based on,

field:value1, value2, value3, ..., valueN

will return any document with at least one value in the collection.



来源:https://stackoverflow.com/questions/14405203/how-to-query-for-terms-in-a-collection-using-lucene-net-similar-to-sqls-in-ope

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!