Question

{
  "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
    }
  ]
}

I am trying to create index for minimal/maximal value for attributes that are stored as list in model above. List contains list of usergroups for product and price value for that group. I want to be able to query that index by filtering with list of provided Usergroups and to get MIN or MAX only for those usergroups that are provided in query.

For instance if User is in groups 934 and 2129 I do not want to calculate value from group 30 in query aggregation so min price should be 24.91, not 14.28 (from group 30).

Was it helpful?

Solution

Calculating the MIN and MAX values in the index will not perform because you would have to calculate for each possible combination of usergroups. But what you can do is map the usergroup price like this and then do a sort on the amountprice either asc or desc depending if you want to have MIN or MAX.

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

The query to get the MIN price for a product for a list of usergroupids would look something like this. (note that I haven't tested this code)

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

This query will not get the documents as results, but the values from the index. In this case the priceAmount because we have said in the index definition it should be stored.

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();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top