RavenDb:更新非规范化引用属性值

bio*_*tal 5 ravendb

我已经实现了RavenDB 非规范化参考模式.我正在努力将静态索引和补丁更新请求连接在一起,以确保在更改引用的实例值时更新我的​​非规范化引用属性值.

这是我的域名:

public class User
{
    public string UserName { get; set; }
    public string Id { get; set; }
    public string Email { get; set; }
    public string Password { get; set; }
}

public class UserReference
{
    public string Id { get; set; }
    public string UserName { get; set; }

    public static implicit operator UserReference(User user)
    {
        return new UserReference
                {
                        Id = user.Id,
                        UserName = user.UserName
                };
    }
}

public class Relationship
{ 
    public string Id { get; set; }
    public UserReference Mentor { get; set; }
    public UserReference Mentee { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

您可以看到UserReference包含引用的用户的Id和UserName.所以现在,如果我更新给定User实例的UserName,那么我希望所有UserReferences中引用的Username值也更新.为此,我编写了一个静态索引和一个补丁请求,如下所示:

public class Relationships_ByMentorId : AbstractIndexCreationTask<Relationship>
{
    public Relationships_ByMentorId()
    {
        Map = relationships => from relationship in relationships
                                select new {MentorId = relationship.Mentor.Id};
    }
}

public static void SetUserName(IDocumentSession db, User mentor, string userName)
{
    mentor.UserName = userName;
    db.Store(mentor);
    db.SaveChanges();

    const string indexName = "Relationships/ByMentorId";
    RavenSessionProvider.UpdateByIndex(indexName,
        new IndexQuery
        {
                Query = string.Format("MentorId:{0}", mentor.Id)
        },
        new[]
        {
                new PatchRequest
                {
                        Type = PatchCommandType.Modify,
                        Name = "Mentor",
                        Nested = new[]
                                {
                                        new PatchRequest
                                        {
                                                Type = PatchCommandType.Set,
                                                Name = "UserName",
                                                Value = userName
                                        },
                                }
                }
        },
        allowStale: false);
}
Run Code Online (Sandbox Code Playgroud)

最后一个UnitTest失败,因为更新没有按预期工作.

[Fact]
public void Should_update_denormalized_reference_when_mentor_username_is_changed()
{
    using (var db = Fake.Db())
    {
        const string userName = "updated-mentor-username";
        var mentor = Fake.Mentor(db);
        var mentee = Fake.Mentee(db);
        var relationship = Fake.Relationship(mentor, mentee, db);
        db.Store(mentor);
        db.Store(mentee);
        db.Store(relationship);
        db.SaveChanges();

        MentorService.SetUserName(db, mentor, userName);

        relationship = db
            .Include("Mentor.Id")
            .Load<Relationship>(relationship.Id);

        relationship.ShouldNotBe(null);
        relationship.Mentor.ShouldNotBe(null);
        relationship.Mentor.Id.ShouldBe(mentor.Id);
        relationship.Mentor.UserName.ShouldBe(userName);

        mentor = db.Load<User>(mentor.Id);
        mentor.ShouldNotBe(null);
        mentor.UserName.ShouldBe(userName);
    }
}
Run Code Online (Sandbox Code Playgroud)

一切运行正常,索引在那里,但我怀疑这不会返回补丁请求所需的关系,但老实说,我已经没有人才了.你能帮帮忙吗?

编辑1

@MattWarren allowStale=true没有帮助.但是我注意到了一个潜在的线索.

因为这是一个单元测试,我使用的是InMemory,嵌入式IDocumentSession - Fake.Db()在上面的代码中.然而,当调用静态索引时UpdateByIndex(...),即在执行时,它使用通用IDocumentStore,而不是特定的伪IDocumentSession.

当我更改索引定义类然后运行我的单元测试时,索引会在"真实"数据库中更新,并且可以通过Raven Studio查看更改.然而,假域实例(mentor,mentee被"拯救"到InMemory DB等)并不存储在实际的数据库(如预期),因此无法通过乌鸦Studio中看到.

可能是我的调用UpdateByIndex(...)是针对错误的IDocumentSession,"真正的"(没有保存的域实例),而不是假的?

编辑2 - @Simon

我已针对上面编辑1中列出的问题实施了修复程序,我认为我们正在取得进展.你是对的,我正在使用静态引用来IDocumentStore通过RavenSessionProvder.现在情况并非如此.下面的代码已更新为使用Fake.Db()替代.

public static void SetUserName(IDocumentSession db, User mentor, string userName)
{
    mentor.UserName = userName;
    db.Store(mentor);
    db.SaveChanges();

    const string indexName = "Relationships/ByMentorId";
    db.Advanced.DatabaseCommands.UpdateByIndex(indexName,
                                        new IndexQuery
                                        {
                                                Query = string.Format("MentorId:{0}", mentor.Id)
                                        },
                                        new[]
                                        {
                                                new PatchRequest
                                                {
                                                        Type = PatchCommandType.Modify,
                                                        Name = "Mentor",
                                                        Nested = new[]
                                                                {
                                                                        new PatchRequest
                                                                        {
                                                                                Type = PatchCommandType.Set,
                                                                                Name = "UserName",
                                                                                Value = userName
                                                                        },
                                                                }
                                                }
                                        },
                                        allowStale: false);
}
}
Run Code Online (Sandbox Code Playgroud)

你会注意到我也重置了allowStale=false.现在当我运行这个时,我收到以下错误:

Bulk operation cancelled because the index is stale and allowStale is false
Run Code Online (Sandbox Code Playgroud)

我想我们已经解决了第一个问题,现在我正在使用正确的Fake.Db,我们遇到了首先突出显示的问题,即索引是陈旧的,因为我们在单元测试中运行超快.

现在的问题是:如何使UpdateByIndex(..)方法等到命令-Q为空并且索引被认为是"新鲜"?

编辑3

考虑到防止陈旧索引的建议,我更新了代码如下:

public static void SetUserName(IDocumentSession db, User mentor, string userName)
{
    mentor.UserName = userName;
    db.Store(mentor);
    db.SaveChanges();

    const string indexName = "Relationships/ByMentorId";

    // 1. This forces the index to be non-stale
    var dummy = db.Query<Relationship>(indexName)
            .Customize(x => x.WaitForNonStaleResultsAsOfLastWrite())
            .ToArray();

    //2. This tests the index to ensure it is returning the correct instance
    var query = new IndexQuery {Query = "MentorId:" + mentor.Id};
    var queryResults = db.Advanced.DatabaseCommands.Query(indexName, query, null).Results.ToArray();

    //3. This appears to do nothing
    db.Advanced.DatabaseCommands.UpdateByIndex(indexName, query,
        new[]
        {
                new PatchRequest
                {
                        Type = PatchCommandType.Modify,
                        Name = "Mentor",
                        Nested = new[]
                                {
                                        new PatchRequest
                                        {
                                                Type = PatchCommandType.Set,
                                                Name = "UserName",
                                                Value = userName
                                        },
                                }
                }
        },
        allowStale: false);
}
Run Code Online (Sandbox Code Playgroud)

从上面编号的评论:

  1. 放入一个虚拟查询来强制索引等到它是非陈旧的工作.消除了有关陈旧指数的错误.

  2. 这是一个测试行,以确保我的索引正常工作.看起来很好.返回的结果是提供的Mentor.Id('users-1')的正确Relationship实例.

    {"Mentor":{"Id":"users-1","UserName":"Mentor先生"},"Mentee":{"Id":"users-2","UserName":"Mr.Mentee "} ...}

  3. 尽管索引是非陈旧的并且看似正常运行,但实际的补丁请求似乎什么也没做.Mentor的非规范化参考中的UserName保持不变.

所以怀疑现在落在补丁请求本身上.为什么这不起作用?这可能是我设置要更新的UserName属性值的方式吗?

...
new PatchRequest
{
        Type = PatchCommandType.Set,
        Name = "UserName",
        Value = userName
}
...
Run Code Online (Sandbox Code Playgroud)

你会注意到我只是userName直接将Value属性的字符串值赋给属性,属性类型RavenJToken.这可能是个问题吗?

编辑4

太棒了!我们有一个解决方案.我已经重新编写了代码以允许您提供的所有新信息(谢谢).为了防止任何人真正读到这一点,我最好把工作代码放到封闭处:

单元测试

[Fact]
public void Should_update_denormalized_reference_when_mentor_username_is_changed()
{
    const string userName = "updated-mentor-username";
    string mentorId; 
    string menteeId;
    string relationshipId;

    using (var db = Fake.Db())
    {
        mentorId = Fake.Mentor(db).Id;
        menteeId = Fake.Mentee(db).Id;
        relationshipId = Fake.Relationship(db, mentorId, menteeId).Id;
        MentorService.SetUserName(db, mentorId, userName);
    }

    using (var db = Fake.Db(deleteAllDocuments:false))
    {
        var relationship = db
                .Include("Mentor.Id")
                .Load<Relationship>(relationshipId);

        relationship.ShouldNotBe(null);
        relationship.Mentor.ShouldNotBe(null);
        relationship.Mentor.Id.ShouldBe(mentorId);
        relationship.Mentor.UserName.ShouldBe(userName);

        var mentor = db.Load<User>(mentorId);
        mentor.ShouldNotBe(null);
        mentor.UserName.ShouldBe(userName);
    }
}
Run Code Online (Sandbox Code Playgroud)

假货

public static IDocumentSession Db(bool deleteAllDocuments = true)
{
    var db = InMemoryRavenSessionProvider.GetSession();
    if (deleteAllDocuments)
    {
        db.Advanced.DatabaseCommands.DeleteByIndex("AllDocuments", new IndexQuery(), true);
    }
    return db;
}

public static User Mentor(IDocumentSession db = null)
{
    var mentor = MentorService.NewMentor("Mr. Mentor", "mentor@email.com", "pwd-mentor");
    if (db != null)
    {
        db.Store(mentor);
        db.SaveChanges();
    }
    return mentor;
}

public static User Mentee(IDocumentSession db = null)
{
    var mentee = MenteeService.NewMentee("Mr. Mentee", "mentee@email.com", "pwd-mentee");
    if (db != null)
    {
        db.Store(mentee);
        db.SaveChanges();
    }
    return mentee;
}


public static Relationship Relationship(IDocumentSession db, string mentorId, string menteeId)
{
    var relationship = RelationshipService.CreateRelationship(db.Load<User>(mentorId), db.Load<User>(menteeId));
    db.Store(relationship);
    db.SaveChanges();
    return relationship;
}
Run Code Online (Sandbox Code Playgroud)

用于单元测试的Raven会话提供程序

public class InMemoryRavenSessionProvider : IRavenSessionProvider
{
    private static IDocumentStore documentStore;

    public static IDocumentStore DocumentStore { get { return (documentStore ?? (documentStore = CreateDocumentStore())); } }

    private static IDocumentStore CreateDocumentStore()
    {
        var store = new EmbeddableDocumentStore
            {
                RunInMemory = true,
                Conventions = new DocumentConvention
                    {
                            DefaultQueryingConsistency = ConsistencyOptions.QueryYourWrites,
                            IdentityPartsSeparator = "-"
                    }
            };
        store.Initialize();
        IndexCreation.CreateIndexes(typeof (RavenIndexes).Assembly, store);
        return store;
    }

    public IDocumentSession GetSession()
    {
        return DocumentStore.OpenSession();
    }
}
Run Code Online (Sandbox Code Playgroud)

索引

public class RavenIndexes
{
    public class Relationships_ByMentorId : AbstractIndexCreationTask<Relationship>
    {
        public Relationships_ByMentorId()
        {
            Map = relationships => from relationship in relationships
                                    select new { Mentor_Id = relationship.Mentor.Id };
        }
    }

    public class AllDocuments : AbstractIndexCreationTask<Relationship>
    {
        public AllDocuments()
        {
            Map = documents => documents.Select(entity => new {});
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

更新非规范化参考

public static void SetUserName(IDocumentSession db, string mentorId, string userName)
{
    var mentor = db.Load<User>(mentorId);
    mentor.UserName = userName;
    db.Store(mentor);
    db.SaveChanges();

    //Don't want this is production code
    db.Query<Relationship>(indexGetRelationshipsByMentorId)
            .Customize(x => x.WaitForNonStaleResultsAsOfLastWrite())
            .ToArray();

    db.Advanced.DatabaseCommands.UpdateByIndex(
            indexGetRelationshipsByMentorId,
            GetQuery(mentorId),
            GetPatch(userName),
            allowStale: false
            );
}

private static IndexQuery GetQuery(string mentorId)
{
    return new IndexQuery {Query = "Mentor_Id:" + mentorId};
}

private static PatchRequest[] GetPatch(string userName)
{
    return new[]
            {
                    new PatchRequest
                    {
                            Type = PatchCommandType.Modify,
                            Name = "Mentor",
                            Nested = new[]
                                    {
                                            new PatchRequest
                                            {
                                                    Type = PatchCommandType.Set,
                                                    Name = "UserName",
                                                    Value = userName
                                            },
                                    }
                    }
            };
}
Run Code Online (Sandbox Code Playgroud)

Sim*_*mon 5

尝试改变你的线路:

RavenSessionProvider.UpdateByIndex(indexName,  //etc
Run Code Online (Sandbox Code Playgroud)

db.Advanced.DatabaseCommands.UpdateByIndex(indexName,  //etc
Run Code Online (Sandbox Code Playgroud)

这将确保在单元测试中使用的同一(假)文档存储上发出更新命令。

编辑2的答案:

使用 UpdateByIndex 时,没有自动方法来等待非过时结果。您的方法有多种选择SetUserName

1 - 将数据存储更改为始终立即更新索引,如下所示(注意:这可能会对性能产生不利影响):

store.Conventions.DefaultQueryingConsistency = ConsistencyOptions.MonotonicRead;
Run Code Online (Sandbox Code Playgroud)

2 - 在 UpdateByIndex 调用之前对索引运行查询,指定选项WaitForNonStaleResults

var dummy = session.Query<Relationship>("Relationships_ByMentorId")
.Customize(x => x.WaitForNonStaleResultsAsOfLastWrite())
.ToArray();
Run Code Online (Sandbox Code Playgroud)

3 - 当索引过时时捕获异常抛出,执行并重Thread.Sleep(100)试。

编辑3的答案:

我终于弄清楚了,并通过了测试......不敢相信,但这似乎只是一个缓存问题。当您重新加载文档进行断言时,您需要使用不同的会话......例如

using (var db = Fake.Db())
{
    const string userName = "updated-mentor-username";
    var mentor = Fake.Mentor(db);
    var mentee = Fake.Mentee(db);
    var relationship = Fake.Relationship(mentor, mentee, db);
    db.Store(mentor);
    db.Store(mentee);
    db.Store(relationship);
    db.SaveChanges();

    MentorService.SetUserName(db, mentor, userName);
}

using (var db = Fake.Db())
{
    relationship = db
        .Include("Mentor.Id")
        .Load<Relationship>(relationship.Id);
    //etc...
}
Run Code Online (Sandbox Code Playgroud)

不敢相信我没有早点发现这一点,抱歉。