gpt4 book ai didi

node.js - "Traditional"RavenDB一对多查询

转载 作者:行者123 更新时间:2023-12-05 01:56:56 26 4
gpt4 key购买 nike

我知道 RavenDB 的 include 特性。它允许我在一次数据库往返中立即获取引用的文档。但我的问题是:我首先获取的文档不包括对“其他”文档的引用。但是“其他”文档有对当前文档的引用。

想象一下我们在世界各地都有站点的设置。每个站点 都可能触发各种警报。每个 alarm 都通过 siteId 引用了 site

现在我想获得所有站点的列表,包括所有警报。但看起来,这对 RavenDB 来说是不可能的?由于 include 仅接受 site 中的“路径”-Document,其中包含引用文档的 id(或 id 数组)。

这可以通过在 site'-document 中提供一组 alarmIds 并在 include 中引用该数组来解决。但是与许多以 orderwithlineItems 为特色的例子相比,其中订单是一个独立的东西,我的 site` 将运行多年,收集 0 到 100 万之间的任何警报。这对我来说似乎是个坏主意。

当然我可以反过来:查询所有警报并通过 sitesIdinclude 站点。但这不会返回警报为零的站点。

那么这只是我这边的设计错误吗?我误解了什么?或者是不可能在一个查询中执行此操作并防止“n+1 查询”?

最佳答案

public class A
{
public string Id { get; set; }
}

public class B
{
public string Id { get; set; }
public string A { get; set; }
}

public class MultiMapIndex : AbstractMultiMapIndexCreationTask<MultiMapIndex.Result>
{
public class Result
{
public string Id { get; set; }
public IEnumerable<string> Bs { get; set; }
}

public MultiMapIndex()
{
AddMap<A>(items => from a in items
select new Result {Id = a.Id, Bs = new string[0]});

AddMap<B>(items => from b in items
select new Result {Id = b.A, Bs = new[] {b.Id}});

Reduce = results => from result in results
group result by result.Id
into g
select new Result {Id = g.Key, Bs = g.SelectMany(r => r.Bs)};
}
}

[Fact]
public async Task TestCase()
{
using var store = GetDocumentStore();

await new MultiMapIndex().ExecuteAsync(store);
using (var session = store.OpenAsyncSession())
{
await session.StoreAsync(new B {A = "a/1"}, "b/0");
await session.StoreAsync(new A(), "a/1");
await session.StoreAsync(new A(), "a/2");
await session.SaveChangesAsync();
}

WaitForIndexing(store);

using (var session = store.OpenAsyncSession())
{
var results = await session.Query<MultiMapIndex.Result, MultiMapIndex>()
.Include(r => r.Bs)
.ToArrayAsync();

var before = session.Advanced.NumberOfRequests;

var bs = session.LoadAsync<B>(results[0].Bs);

Assert.Equal(before, session.Advanced.NumberOfRequests);
}
}

关于node.js - "Traditional"RavenDB一对多查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69664686/

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