开发者

Lucene.NET and lazy loading

Here's a tricky question: 开发者_如何学GoI want to do lazy loading over a Lucene search result. Possible?

Here's my code:

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

Consuming code:

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

My question is, how can I lazy-load search results from Lucene?


After toying with a few options, I've figured out the answer: use the 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();
   }
}

With the yield return iterator, the searcher doesn't get disposed until consumers are done with their evaluations. Brilliant! Lazy loaded search results from Lucene, exactly what I was looking for. Wahoo! :-)


Have a look at the HitCollector object. E.g. http://rosowski.wordpress.com/2008/07/29/lucene-using-the-hitcollector/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜