使用RavenDb索引查找完整序列 [英] Finding complete sequences using a RavenDb index

查看:63
本文介绍了使用RavenDb索引查找完整序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在RavenDb中有一些文档,看起来可能像这样:

I have documents in RavenDb that may look something like this:

{ "Id": "obj/1", "Version": 1 },
{ "Id": "obj/1", "Version": 2 },
{ "Id": "obj/1", "Version": 3 },
{ "Id": "obj/1", "Version": 4 },
{ "Id": "obj/2", "Version": 1 },
{ "Id": "obj/2", "Version": 2 },
{ "Id": "obj/2", "Version": 3 },
{ "Id": "obj/3", "Version": 1 },
{ "Id": "obj/3", "Version": 3 }

我正在尝试创建一个索引,该索引将给我:

I'm trying to create an index that would give me:

  • "obj/1"和"obj/2"序列,最好按ID分组.
  • 不是序列"obj/3",因为它尚未完成

我该怎么做?

推荐答案

我设法解决了这个问题.我不确定这是否是最佳解决方案,但它似乎可以正常工作.

I managed to solve it. I'm not sure it is the optimal solution but it seems to work.

class SequenceIndex : AbstractIndexCreationTask<MyObject>
{
    public EventSequenceIndex()
    {
        Map = objects => from d in docs
                         orderby d.Version
                         select new
                         {
                             Id = d.Id,
                             Version = d.Version
                         };

        TransformResults = (database, results) => 
            from result in results
            group result by result.Id into g
            where g.Select(d => d.Version + 1)
               .Except(g.Select(d => d.Version))
               .Count() == 1
            select new
            {
                Id = g.Key,
                Objects = g
            };
    }
}

带有查询:

var events = session.Query<MyObject, SequenceIndex>()
    .As<MySequenceObjectView>()
    .ToArray();

我按ID对文档进行分组,然后取除所有version的所有version + 1,对于1, 2, 3的原始序列将为2, 3, 4 except 1, 2, 3,这给了我4(这就是为什么我使用Count() == 1.但是,如果序列中有一个空洞,则计数将大于1,因此将其从结果中排除.

I group the documents by Id and then take all version + 1 except all version, which for an original sequence of 1, 2, 3 will be 2, 3, 4 except 1, 2, 3, which gives me 4 (which is why I use the Count() == 1. But if there is a hole in the sequence, the count would be greater than 1, and therefore excluded from the results.

这篇关于使用RavenDb索引查找完整序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆