Querying a child collection by multiple values in RavenDB

前端 未结 3 2007
野性不改
野性不改 2021-01-02 20:21

I\'m using RavenDB build 371 and I have the following model:

class Product {
 public string Id { get; set; }
 public ProductSpec[] Specs { get; set; }
}

cla         


        
3条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-02 20:45

    I've changed the model a bit and was able to achieve the desired result using the Project method in AbstractIndexCreationTask. This is the (simplified) data model:

    public class Product
    {
        public string Id { get; set; }
        public int CategoryId { get; set; }
        public int TotalSold { get; set; }
        public Dictionary Specs { get; set; }
    }
    

    This is the index definition:

    public class Products_ByCategoryIdAndSpecs_SortByTotalSold : AbstractIndexCreationTask
    {
        public Products_ByCategoryIdAndSpecs_SortByTotalSold()
        {
            this.Map = products => from product in products
                                   select new
                                   {
                                       product.CategoryId,
                                       _ = Project(product.Specs, spec => new Field("Spec_" + spec.Key, spec.Value, Field.Store.NO, Field.Index.ANALYZED)),
                                       product.TotalSold
                                   };
        }
    }
    

    Then I can query like so:

        var results = session.Advanced.LuceneQuery()
            .WhereEquals("CategoryId", 15920)
            .AndAlso().WhereEquals("Spec_Class", "3A")
            .AndAlso().WhereEquals("Spec_Finish", "Plain")
            .OrderBy("-TotalSold")
            .ToList(); 
    

    This will return the products in category "15920" which have a "Class" spec value of "3A" and a "Finish" spec value of "Plain" sorted in descending order by the total units sold.

    The key was using the Project method which basically creates fields in the Lucene document for each spec name-value pair.

提交回复
热议问题