Creating Query Objects

As your Lucene queries become more complex you may see benefit in abstracting them into separate query objects.

SimpleLucene has a query base class (QueryBase) that you can use to create query objects. Here's an example for querying Products:

    public class ProductQuery : QueryBase
    {
        public ProductQuery(Query query) : base(query) { }

        public ProductQuery() { }

        public ProductQuery WithKeywords(string keywords)
        {
            if (!string.IsNullOrEmpty(keywords))
            {
                string[] fields = { "name", "description" };
                var parser = new MultiFieldQueryParser(Version.LUCENE_29,
                    fields, new StandardAnalyzer(Version.LUCENE_29));
                Query multiQuery = parser.Parse(keywords);

                this.AddQuery(multiQuery);
            }
            return this;
        }

        public ProductQuery WithPriceBetween(decimal? minPrice, decimal? maxPrice)
        {
            if (minPrice.HasValue && maxPrice.HasValue)
            {
                if (minPrice.Value >= 0 && maxPrice.Value > 0)
                {
                    var rangeQuery = NumericRangeQuery.NewFloatRange("price",
                        (float)minPrice.Value, (float)maxPrice.Value, true, true);

                    this.AddQuery(rangeQuery);
                }
            }
            return this;
        }
    }

The WithKeywords method constructs a query using the Lucene StandardAnalyzer. This is great for search boxes so you can enter search terms like "trainers AND nike NOT running" (for more details see http://lucene.apache.org/java/2_3_2/queryparsersyntax.html).

We can then query the index creating in the index examples like so:

            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(query.Query);
                foreach (var doc in result.Results)
                    Console.WriteLine(doc.GetValue("name"));
                Console.ReadLine();
            }

This will output:
Football
Trainers
DVD

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

Comments

No comments yet.