如何使用FaunaDB中的UDF在输入数组上循环



我有一个关于映射ID(inputdata(数组并将所有相关文档返回到这些ID的问题。我设置了一个UDF来检索单个ID的文档,并希望通过一些调整来实现这一点。我似乎不知道如何映射输入数据并创建一个变量(data:(来存储新的文档数组。感谢您的帮助。以下是工作的单条目UDF:

Query(
Lambda(
["inputdata"],
Let(
{
data: Map(
Paginate(
Match(
Index("certificate_by_dealer"),
Ref(Collection("Dealers"), Select("dealer", Var("inputdata")))
)
),
Lambda(["ref"], Get(Var("ref")))
)
},
Select(["data"], Var("data"))
)
)
)

有没有一个简单的。。。或者有什么解决方案可以让ID的数组作为输入数据?

调用功能为:

Call("user_dealers_all_certificates", {
ids: [301393590798516736, 301393590798516749]
}

不幸的是,我没有得到任何结果。(添加报价解决了问题(

以下是实现建议的UDF:

Query(
Lambda(
["inputdata"],
Let(
{ dataIds: Select("ids", Var("inputdata")) },
Union(
Map(
Var("dataIds"),
Lambda(
["id"],
Select(
["data"],
Paginate(
Match(
Index("certificate_by_dealer"),
Ref(Collection("Dealers"), Var("id"))
)
)
)
)
)
)
)
)
)

添加引号创建了正确的响应:

Call("user_dealers_all_certificates", {ids: ["302122229239382536", "301394099049595400"]})
[
Ref(Collection("Certificate"), "302122488174739977"),
Ref(Collection("Certificate"), "302120872550859273")
]

但是GraphQL查询返回错误数据:

query {
allUserDealersCertificate(data: {ids: ["302122229239382536", "301394099049595400"]}){
data {
_id
}
}
}

响应:

{
"errors": [
{
"message": "Lambda expects an array with 1 elements. Array contains 4.",
"extensions": {
"code": "invalid argument"
}
}
]
}

没有分页的GraphQL错误:架构中为true:

{
"data": {
"allUserDealersCertificate": [
null,
null
]
},
"errors": [
{
"message": "Cannot return null for non-nullable type (line 3, column 5):n    _idn    ^",
"path": [
"allUserDealersCertificate",
0,
"_id"
],
"locations": [
{
"line": 3,
"column": 5
}
]
},
{
"message": "Cannot return null for non-nullable type (line 3, column 5):n    _idn    ^",
"path": [
"allUserDealersCertificate",
1,
"_id"
],
"locations": [
{
"line": 3,
"column": 5
}
]
}
]
}

根据您提供的查询,我觉得有必要指出Match函数执行完全匹配。它不会(也不能(为您展开结构化数组。Ref也不能工作。

您需要在inputdata上调用Map,并获得每个id的结果。然后,您可以将这些结果Union合并到一个列表中。

我不知道你正在处理的数据的确切形状,所以这里有一个查询,可以使用仪表板中可用的预填充数据:

Let(
{
// the pre-populated data has 3 stores, with ids 301, 302, and 303
// here, we want the products in stores 301 and 302
ids: [ 301, 302 ]
},
// this is where we combine all of the results
Union(
Map(
// here is where we loop over the list of ids
Var("ids"),
Lambda(
// for each id, run this function's expression
"id",
Select(
// each Paginate call returns a page of results with its own data
// field, so we have to select those out
"data",
Paginate(
Match(
Index("products_by_store"),
// here we compose a reference to a specific store, using the
// Lambda function's current id
Ref(Collection("stores"), Var("id"))
)
)
)
)
)
)
)

Npte,我已经使用Let来模拟将数组传递到UDF的主体。当您运行此查询时,结果应该是:

[
["avocados", "Conventional Hass, 4ct bag", 3.99],
["cilantro", "Organic, 1 bunch", 1.49],
["limes", "Conventional, 1 ct", 0.35],
["limes", "Organic, 16 oz bag", 3.49],
["cups", "Translucent 9 Oz, 100 ct", 6.98],
["pinata", "Giant Taco Pinata", 23.99],
["pinata", "Original Classic Donkey Pinata", 24.99]
]

最新更新