This project is read-only.

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

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

            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

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)

This will output:

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


No comments yet.