这是一个棘手的问题:我想对Lucene搜索结果进行延迟加载。可能?
这是我的代码:
public IEnumerable<BizObj> Search(string query)
{
var parsedQuery = new QueryParser(...).Parse();
var searcher = new IndexSearcher(parsedQuery, storage);
try
{
var hits = searcher.Search(parsedQuery);
// Hooray for LINQ's lazy-evaluated Select method!
// But oh noes!! searcher will be closed by the time it
// gets executed, thus resulting in an exception. :-(
return hits.Select(hit => PullBizObjectFromDatabase(hit));
}
finally
{
searcher.Close();
}
}
消耗代码:
var searchResults = from result in blah.Search("hello, world!")
where SomeBizLogic(result)
select result;
// Print the top 50 search results.
foreach (var result in searchResults.Take(50))
{
// Exception! The searcher field inside Search(...) has been closed! :-(
Console.WriteLine(result);
}
我的问题是,我如何延迟加载Lucene的搜索结果?
答案 0 :(得分:2)
在玩了几个选项之后,我找到了答案:使用yield return iterator:
public IEnumerable<BizObj> Search(string query)
{
var parsedQuery = new QueryParser(...).Parse();
var searcher = new IndexSearcher(parsedQuery, storage);
try
{
var hits = searcher.Search(parsedQuery);
foreach (var hit in hits)
{
yield return PullBizObjectFromDatabase(hit);
}
}
finally
{
searcher.Close();
}
}
使用yield return iterator,搜索者在消费者完成评估之前不会被处理。辉煌!来自Lucene的延迟加载搜索结果,正是我所寻找的。嗬! : - )
答案 1 :(得分:1)
查看HitCollector对象。 例如。 http://rosowski.wordpress.com/2008/07/29/lucene-using-the-hitcollector/