使用过滤器聚合列表的Ravendb索引

时间:2014-03-27 07:59:39

标签: ravendb

{
  "Id": "products/214429",
  "Title": "RADIO SYMPHONY ORCHESTR - VERDI: OPERA CHORUSES",
  "CategoryId": 91166,
  "CategoryName": "Classical",
  "Prices": [
    {
      "UserGroupId": 2129,
      "PriceAmount": 24.91
    },
    {
      "UserGroupId": 934,
      "PriceAmount": 34.91
    },
    {
      "UserGroupId": 30,
      "PriceAmount": 14.28
    }
  ]
}

我正在尝试为上面模型中存储为列表的属性创建最小/最大值的索引。列表包含该组的产品和价格值的用户组列表。我希望能够通过使用提供的用户组列表进行过滤来查询该索引,并仅为查询中提供的那些用户组获取MIN或MAX。

例如,如果用户在组934和2129中,我不想在查询聚合中计算组30的值,因此最低价格应为24.91,而不是14.28(来自组30)。

1 个答案:

答案 0 :(得分:1)

计算索引中的MIN和MAX值将不会执行,因为您必须为每个可能的用户组组合进行计算。但你可以做的是像这样映射用户组价格,然后根据你想要MIN或MAX的数量来定价asc或desc。

public class ProductUserGroupPrices : AbstractIndexCreationTask<Product, Product>
{
    public ProductUserGroupPrices()
    {
        Map = products => from product in products
                      from price in product.Prices
                      select new 
                      {
                          UserGroupId = price.UserGroupId
                          PriceAmount = price.PriceAmount,
                          ProductId = product.Id
                      };

        Sort(x => x.PriceAmount, SortOptions.Double);
        Stores.Add(x => x.PriceAmount, FieldStorage.Yes);
    }
}

获取用户组ID列表的产品的MIN价格的查询看起来像这样。 (请注意,我还没有测试过此代码)

public class ProductUserGroupPrice
{
    public double PriceAmount { get; set; }
}

此查询不会将文档作为结果获取,而是从索引中获取值。在这种情况下,priceAmount因为我们在索引定义中说过它应该存储。

var results = session.Advanced.LuceneQuery<Product>("ProductUserGroupPrices")
       .SelectFields<ProductUserGroupPrice>()
       .WhereEquals(x => x.ProductId, productId)
       .AndAlso()
       .WhereIn(x => x.UserGroupId, userGroupIds)
       .OrderBy(x => x.PriceAmount)
       .FirstOrDefault();