RavenDB 计数索引包括零值
RavenDB count index including zero values
我有一个项目列表 {Id, Name, CategoryId}
和一个类别列表 {Id, Name, IsActive}
。
如何获取列表 {CategoryId, Count}
包括具有零项的类别。
目前我有这样的索引:
public class CategoryCountIndex : AbstractIndexCreationTask<Item, CategoryCountIndex.Result>
{
public class Result
{
public string CategoryId { get; set; }
public int Count { get; set; }
}
public CategoryCountIndex()
{
Map = items => from item in items
select new Result
{
CategoryId = item.CategoryId,
Count = 1
};
Reduce = results => from result in results
group result by result.CategoryId
into c
select new Result
{
CategoryId = c.Key,
Count = c.Sum(x => x.Count)
};
}
}
improve/change我的解决方案的最佳方法是什么?
我删除了我之前的回答,因为它被证明是不正确的。在这种情况下,您实际上可以使用 MultiMap/Reduce 索引来解决您的问题。
尝试使用以下索引:
public class Category_Items : AbstractMultiMapIndexCreationTask<Category_Items.ReduceResult>
{
public class ReduceResult
{
public string CategoryId { get; set; }
public int Count { get; set; }
}
public Category_Items()
{
AddMap<Item>(items =>
from item in items
select new
{
CategoryId = item.CategoryId,
Count = 1
});
AddMap<Category>(categories =>
from category in categories
select new
{
CategoryId = category.Id,
Count = 0
});
Reduce = results =>
from result in results
group result by result.CategoryId into g
select new ReduceResult
{
CategoryId = g.Key,
Count = g.Sum(x => x.Count)
};
}
}
这将导致以下结果(三个类别,但一个没有项目):
现在,如果要显示类别名称,您可以使用结果转换器。
希望对您有所帮助!
我有一个项目列表 {Id, Name, CategoryId}
和一个类别列表 {Id, Name, IsActive}
。
如何获取列表 {CategoryId, Count}
包括具有零项的类别。
目前我有这样的索引:
public class CategoryCountIndex : AbstractIndexCreationTask<Item, CategoryCountIndex.Result>
{
public class Result
{
public string CategoryId { get; set; }
public int Count { get; set; }
}
public CategoryCountIndex()
{
Map = items => from item in items
select new Result
{
CategoryId = item.CategoryId,
Count = 1
};
Reduce = results => from result in results
group result by result.CategoryId
into c
select new Result
{
CategoryId = c.Key,
Count = c.Sum(x => x.Count)
};
}
}
improve/change我的解决方案的最佳方法是什么?
我删除了我之前的回答,因为它被证明是不正确的。在这种情况下,您实际上可以使用 MultiMap/Reduce 索引来解决您的问题。
尝试使用以下索引:
public class Category_Items : AbstractMultiMapIndexCreationTask<Category_Items.ReduceResult>
{
public class ReduceResult
{
public string CategoryId { get; set; }
public int Count { get; set; }
}
public Category_Items()
{
AddMap<Item>(items =>
from item in items
select new
{
CategoryId = item.CategoryId,
Count = 1
});
AddMap<Category>(categories =>
from category in categories
select new
{
CategoryId = category.Id,
Count = 0
});
Reduce = results =>
from result in results
group result by result.CategoryId into g
select new ReduceResult
{
CategoryId = g.Key,
Count = g.Sum(x => x.Count)
};
}
}
这将导致以下结果(三个类别,但一个没有项目):
现在,如果要显示类别名称,您可以使用结果转换器。
希望对您有所帮助!