Searching an Index
To search an index using SimpleLucene you use the SearchService. Like the IndexService, SearchService implements IDisposable so you should make sure you call Dispose() when you are done with it.
SearchService has both generic and non generic SearchIndex methods. The non generic version returns a result object containing Lucene documents. The generic version allows you to
specify a result definition to convert the Lucene documents to strongly typed objects.
The example below shows how we can search the index created in the
Indexing examples. It uses the non generic SearchIndex method:
var indexSearcher = new DirectoryIndexSearcher(new DirectoryInfo(indexPath), true);
using (var searchService = new SearchService(indexSearcher)) {
var result = searchService.SearchIndex(new TermQuery(new Term("id", "1")));
var luceneDocs = result.Results;
Console.Write(luceneDocs.First().GetValue("name"));
Console.ReadLine();
}
The output would be "Football" since this is the name of the product in our static repository with Id = 1.
Here we are searching using a simple TermQuery. For complex queries you are better off creating your own Query object (see
Creating Query Objects).
SimpleLucene has a few extension methods for working with Lucene Documents like GetValue(string field) and GetValue<T>(string field) for returning strongly typed results.