mbrb
mbrb

Reputation: 403

How to group a set of filter operators in a RavenDB query?

For filtering products in RavenDB I use a generic list of product filters - to a avoid a long switch.

The product filter class looks like:

public class ProductFilter
{
    public string FilterName { get; set; }
    public List<string> FilterValues { get; set; }

    public ProductFilter()
    {
        FilterValues = new List<string>();
    }
}

The FilterName is equal to index property name

I use this index for querying products:

public class CategoryProducts_Index : AbstractIndexCreationTask<Product, CategoryProducts_Index.ReduceResult>
{
    public class ReduceResult
    {
        public string Category { get; set; }
        public string Title { get; set; }
        public string Brand { get; set; }
        public decimal RegularPrice { get; set; }
    }

    public CategoryProducts_Index()
    {
        Map = products =>
              from p in products
              from c in p.Categories
              select new
              {
                  Category = c,
                  Title = p.Title,
                  Brand = p.Brand,
                  RegularPrice = p.RegularPrice
              };
    }
}

For a generic solution to filter products by looping a list of ProductFilter, I want to achieve a Lucene query grouping like:

Category: parent_category AND  (Category: sub_category_1 OR Category: sub_category_2 OR ...etc) AND (Brand: brand1 OR Brand:brand2 OR ...etc)

With a normal Linq Query I could not retrieve an index property by string name, so I tried to do that with LuceneQuery as follows:

public IDocumentQuery<Product> GetProductsBySelectedFilters(string category, List<ProductFilter> productFilters)
    {
        IDocumentQuery<Product> products;
        using (var session = DocumentStore.OpenSession())
        {
            products = session.Advanced.LuceneQuery<Product>("CategoryProducts/Index", isMapReduce: true)
                .WhereStartsWith("Category", category);

            foreach (var filter in productFilters)
            {
                products.UsingDefaultOperator(QueryOperator.And);
                foreach (var value in filter.FilterValues)
                {
                    products.WhereEquals(filter.FilterName, value);
                    products.UsingDefaultOperator(QueryOperator.Or);
                }
            }
        }
        return products;
    }

The Lucene output query of this, is like:

Category: parent_category Category: sub_category_1 Category: sub_category_2 Brand: brand1  Brand: brand2  ...etc

That's not what I expected

Someone any idea how to handle this?

Upvotes: 1

Views: 401

Answers (1)

synhershko
synhershko

Reputation: 4492

Use LuceneQuery's .OpenSubclause() and .CloseSubclause()

Upvotes: 1

Related Questions