为什么Lucene数值范围搜索不起作用?

时间:2013-06-28 06:39:09

标签: c# lucene.net

传递给搜索的字符串i(Experience:[1 TO 5]),搜索所有数字,如15,25,21,51等。我需要在数字1和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();

1 个答案:

答案 0 :(得分:7)

要执行范围类型查询,

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

但是,如果您将数字存储为string,那么可能会返回错误的范围,因为它会进行字符串比较,而不是数字比较;因此"5" > "15"true,而不是相反。

要执行数字范围类型查询,

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

但是,您需要确保在索引文档时,将Experience字段存储为数字字段而不是标准字段,

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

将其添加到Lucene文档之前。