我尝试了以下方法来组合查询,但我不知道如何在这些查询中添加(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);
答案 0 :(得分:6)
使用Lucene.NET实现AND
,OR
和NOT
功能的最简单方法是使用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);