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

本文关键字:查询 组合 运算符 术语 数字 Lucene NET | 更新日期: 2023-09-27 18:20:36

我尝试了以下方法来组合查询,但我不知道如何在这些查询中添加(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);

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

使用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);