如何在Lucene.NET中使用运算符组合术语查询和数字查询?

时间:2013-07-01 08:23:56

标签: c# lucene.net

我尝试了以下方法来组合查询,但我不知道如何在这些查询中添加(AND,OR,NOT)运算符。

BooleanQuery booleanQuery = new BooleanQuery();
Query query1 = new TermQuery(new Term("Skill_Summary", "Java"));
Query pageQueryRange = NumericRangeQuery.NewIntRange("Experience", 1, 2, true, true);
booleanQuery.Add(query1, BooleanClause.Occur.MUST);
booleanQuery.Add(pageQueryRange, BooleanClause.Occur.MUST);
var hits = searcher.Search(booleanQuery);

以上booleanQuery的结果+Skill_Summary:Java +Experience:[1 TO 2]仍无法获得结果

String termQueryString = "Skill_Summary:\"Java\"";
Query termQuery = queryParser.Parse(termQueryString);
Query QueryRange = NumericRangeQuery.NewIntRange("Experience", 1, 3, true, true);
Query query = termQuery.Combine(new Query[] { termQuery, QueryRange });
var hits = searcher.Search(query);

1 个答案:

答案 0 :(得分:6)

使用Lucene.NET实现ANDORNOT功能的最简单方法是使用BooleanQuery类组合查询。将查询添加到booleanQuery时,可以使用Occur参数指定应如何处理查询,

var termQuery = new TermQuery(new Term("Skill_Summary", "Java"));
var booleanQuery = new BooleanQuery();

// Use 'Occur.MUST` to simulate an AND, or '+Skill_Summary:Java'
booleanQuery.Add(termQuery, Occur.MUST);

// Use 'Occur.SHOULD` to simulate an OR, or just 'Skill_Summary:Java'
booleanQuery.Add(termQuery, Occur.SHOULD);

// Use 'Occur.MUST_NOT` to simulate a NOT, or just '-Skill_Summary:Java'
booleanQuery.Add(termQuery, Occur.MUST_NOT);

在您的示例中,您可能会发现TermQuery尝试按字面意义匹配值,因此它不会匹配“java”或“Java”之类的值。要做到这一点,你需要做,

var booleanQuery = new BooleanQuery();

// Use QueryParser
var query1 = new QueryParser(version, "Skill_Summary", analyzer).Parse("Java");
var pageQueryRange = NumericRangeQuery.NewIntRange("Experience", 1, 2, true, true);
booleanQuery.Add(query1, BooleanClause.Occur.MUST);
booleanQuery.Add(pageQueryRange, BooleanClause.Occur.MUST);
var hits = searcher.Search(booleanQuery);