RavenDB计数索引包括零值

时间:2015-05-11 20:35:16

标签: c# mapreduce ravendb nosql

我有一个项目列表{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)
            };
    }
}

改善/更改我的解决方案以获得没有项目的类别的最佳方法是什么?

1 个答案:

答案 0 :(得分:1)

我删除了我之前的答案,因为它被证明是不正确的。在这种情况下,您实际上可以使用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)
            };
    }
}

这将产生以下结果(三个类别,但一个没有项目): Query result from index

现在,如果要显示“类别名称”,则可以使用“结果转换器”。

希望这有帮助!