Using Result Definitions

Often you will want to cast the results of a Lucene search to a strongly typed result object.

SimpleLucene provides the IResultDefinition for this purpose. This is similar to the IIndexDefinition, but this time we are defining how to convert a Lucene document to our result object.

Below is a definition for our product search results:

    public class ProductResultDefinition : IResultDefinition<Product> {
        public Product Convert(Document document) {
            var product = new Product();
            product.Id = document.GetValue<int>("id");
            product.Name = document.GetValue("name");
            product.Price = document.GetValue<decimal>("price");

            return product;
        }
    }

We can then update the code from our previous example to use our result definition. This time we use the generic SearchIndex method, specifying the result type that we want to return, along with our result definition:

            var indexSearcher = new DirectoryIndexSearcher(new DirectoryInfo(indexPath), true);
            using (var searchService = new SearchService(indexSearcher)) {
                var query = new ProductQuery().WithPriceBetween(0, 100);
                var result = searchService.SearchIndex<Product>(query.Query, new ProductResultDefinition());
                foreach (var p in result.Results)
                    Console.WriteLine(p.Name);
                Console.ReadLine();
            }

The SearchResult object returned by the SearchIndex method also contains the original Lucene documents (Documents property), if you wish to work with them directly.

Last edited Feb 6, 2011 at 2:36 PM by retroviz, version 4

Comments

No comments yet.