Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Lucene numeric range search not working?

Tags:

c#

lucene.net

The string i passed to search is (Experience:[1 TO 5]) where it searches all the numbers like 15, 25, 21, 51, etc. I need to search between the number 1 and 5,

using Lucene.Net.Store;

var results = new List<SearchResults>();

// Specify the location where the index files are stored
string indexFileLocation = @"G:\Lucene.Net\Data\Document";
var dir = Lucene.Net.Store.FSDirectory.GetDirectory(indexFileLocation);
var reader = IndexReader.Open(dir);
var searcher = new IndexSearcher(reader);
var analyzer = new StandardAnalyzer();
var queryParser = new QueryParser("Prof_ID", analyzer);

// <default field> is the field that QueryParser will search if you don't 

string special = "";
if (!txtkeyword.Text.Equals(""))
{
    special = special + "(Experience:[1 TO 5])";
}

var hits = searcher.Search(queryParser.Parse(special));

// Getting result to the list
for (int i = 0; i < hits.Length(); i++)
{
    SearchResults result = new SearchResults();

    result.Skillsummarry = hits.Doc(i).GetField("JS_Skill_Summary").StringValue();
    result.Experience = hits.Doc(i).GetField("Experience").StringValue();
    result.Profile_Id = hits.Doc(i).GetField("Prof_ID").StringValue();

    results.Add(result);
}

GridView1.DataSource = results;
GridView1.DataBind();
like image 335
Dinesh_Dini Avatar asked Jun 28 '13 06:06

Dinesh_Dini


1 Answers

To do a range-type query you should do,

var query = new TermRangeQuery(
    "Experience", 
    "1", 
    "5", 
    includeLower: true, 
    includeUpper: true);

However, that's if you stored your numbers as string which might return wrong ranges as it does a string comparison, not a numeric comparison; thus "5" > "15" is true, instead of the other way around.

To do a numeric range-type query you do,

var query = 
    NumericRangeQuery.NewDoubleRange(
        "Experience", 
        1, 
        5, 
        includeLower: true, 
        includeUpper: true);

However, you need to make sure when you index your documents, you store the Experience field as a numeric field rather than a standard one,

var field = 
    new NumericField("Experience", Field.Store.YES, true)
        .SetDoubleValue(15, 25, 21, 51, etc. );

before adding it to your Lucene document.

like image 178
rae1 Avatar answered Oct 09 '22 14:10

rae1