Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Combine term query and numeric query using operators in Lucene.NET?

Tags:

c#

lucene.net

I have tried the following methods to combine the query but I don't know how to add (AND,OR,NOT) operator in these query.

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

The result of the above booleanQuery is +Skill_Summary:Java +Experience:[1 TO 2] still not getting the result

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);
like image 470
Dinesh_Dini Avatar asked Mar 24 '23 08:03

Dinesh_Dini


1 Answers

The easiest way to achieve AND, OR and NOT functionality using Lucene.NET is to combine queries using the BooleanQuery class. When you add your queries to the booleanQuery you can use the Occur argument to specify how the query should be treated,

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

In your example, you might find that the TermQuery tries to match the value literally, so it won't match values like "java" or "Java". To do that you will need to do,

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);
like image 94
rae1 Avatar answered Mar 25 '23 23:03

rae1