gpt4 book ai didi

RavenDB 补丁 API : updating a nested collection

转载 作者:行者123 更新时间:2023-12-04 10:27:48 24 4
gpt4 key购买 nike

我正在尝试使用 Patch API 更新嵌套集合。更具体地说,请考虑以下示例 - Posts 集合:

{
"Title": "Hello RavenDB",
"Category": "RavenDB",
"Content": "This is a blog about RavenDB",
"Comments": [
{
"Title": "Unrealistic",
"Content": "This example is unrealistic"
},
{
"Title": "Nice",
"Content": "This example is nice"
}
]
}

我在 http://ravendb.net/docs/client-api/partial-document-updates 使用了 Patch API 和基于 Set 的操作文档和 http://ravendb.net/docs/client-api/set-based-operations以及几个 stackoverflow 问题作为使用集合操作和静态索引进行批量更新的资源。一个要求是仅当先前的值为“Nice”时才更新评论的“Title”,如果是,则将其更新为“Bad”。

静态索引“NicePosts”定义为:
Map = posts => from post in posts    
where post.Comments.Any(comment => comment.Title == "Nice")
select new {post.Title, post.Category}

批量补丁更新命令是:
    documentStore.DatabaseCommands.UpdateByIndex("NicePosts",   
new IndexQuery(),
new[] { new PatchRequest
{ Type = PatchCommandType.Modify,
Name = "Comments",
PrevVal = RavenJObject.Parse(@"{ ""Title"": ""Nice""}"),
Nested = new[]
{
new PatchRequest {Type = PatchCommandType.Set, Name = "Title", Value = new RavenJValue("Bad") },
} }, allowStale: true);

我对此有一些疑问:

1) 我的更新命令的结构/语法是否正确?

2) 我希望对集合中的所有记录执行更新。因此我没有在 IndexQuery Query 中定义查询过滤器,因为“NicePosts”索引已经返回了适当的集合。但是,运行此命令不会更新集合。

3) 如果我设置了“allowStale:false”,我会收到“stale index”错误。在打开我的文档存储 session 之前,我实例化索引类并执行它以将它持久化到 ravenDB 实例。任何想法这里出了什么问题?

谢谢,

编辑:

根据 ayende 的建议,将 Patch 命令更改为:
 documentStore.DatabaseCommands.UpdateByIndex("NicePosts",
new IndexQuery(),
new[] {
new PatchRequest {
Type = PatchCommandType.Modify,
Name = "Comments",
Position = 0,
Nested = new[] {
new PatchRequest {Type = PatchCommandType.Set, Name = "Title", Value = new RavenJValue("Bad")},
}
}
}, allowStale: false);

最佳答案

这现在可以使用 scripted patch request 来完成。 :

string oldTitle = "Nice";
string newTitle = "Bad";

documentStore.DatabaseCommands.UpdateByIndex("NicePosts",
new IndexQuery(),
new ScriptedPatchRequest
{
Script = @"for (var i = 0; i < this.Comments.length; i++)
if (this.Comments[i].Title == oldTitle)
this.Comments[i].Title = newTitle;",
Values =
{
{ "oldTitle", oldTitle },
{ "newTitle", newTitle },
},
}
);

关于RavenDB 补丁 API : updating a nested collection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10592470/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com