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

后端 未结 2 1381
无人及你
无人及你 2020-12-19 22:55

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

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


        
相关标签:
2条回答
  • 2020-12-19 23:43

    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;
    }
    
    0 讨论(0)
  • 2020-12-19 23:47

    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.

    0 讨论(0)
提交回复
热议问题