【问题标题】:RavenDB count index including zero valuesRavenDB 计数索引,包括零值
【发布时间】:2015-05-11 20:35:16
【问题描述】:

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

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

【问题讨论】:

    标签: c# mapreduce ravendb nosql


    【解决方案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)
                };
        }
    }
    

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

    如果您想显示类别名称,现在可以使用结果转换器。

    希望这会有所帮助!

    【讨论】:

    • 这正是我所需要的。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2012-06-29
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 2019-06-24
    • 2020-12-24
    • 2020-12-12
    • 2020-11-10
    相关资源
    最近更新 更多