如何构建Lucene查询x AND(y OR z)

时间:2012-05-17 16:10:49

标签: c# lucene lucene.net

我正在尝试为Lucene创建一个查询,如下所示

word:“searching_word”AND(类别:0 OR类别:1)

search_word必须在单词字段和类别字段中的含义为0或1。

字段是普通字段类型 category字段是NumericField类型

    BooleanQuery mainQuery = new BooleanQuery();

    Query query1 = new TermQuery(new Term("category", NumericUtils.IntToPrefixCoded(0)));
    Query query2 = new TermQuery(new Term("category", NumericUtils.IntToPrefixCoded(1));

    Query queryTerm= new TermQuery(new Term("word", searchedWord));


    mainQuery.Add(queryTerm, BooleanClause.Occur.MUST);

    BooleanQuery innerOrQuery = new BooleanQuery();

    //How do i add them as OR and as AND to mainQuery
    innerOrQuery.Add(querySingleDirection, BooleanClause.Occur.MUST);
    innerOrQuery.Add(queryBothDirection, BooleanClause.Occur.MUST);
     mainQuery.Add(innerOrQuery, BooleanClause.Occur.MUST);
    TopDocs topDocs = _indexSearcher.Search(mainQuery, Settings.Current.MaximumTopScoreCount);

1 个答案:

答案 0 :(得分:0)

Query queryTerm = new TermQuery(new Term("word", searchedWord));
Query query1 = new TermQuery(new Term("category", NumericUtils.IntToPrefixCoded(0)));
Query query2 = new TermQuery(new Term("category", NumericUtils.IntToPrefixCoded(1));

BooleanQuery innerOrQuery = new BooleanQuery();
innerOrQuery.Add(query1, BooleanClause.Occur.SHOULD);
innerOrQuery.Add(query2, BooleanClause.Occur.SHOULD);

BooleanQuery mainQuery = new BooleanQuery();
mainQuery.Add(queryTerm, BooleanClause.Occur.MUST);
mainQuery.Add(innerOrQuery, BooleanClause.Occur.MUST);

TopDocs topDocs = _indexSearcher.Search(mainQuery, Settings.Current.MaximumTopScoreCount);