aws-amplify - 如何过滤数据忽略不匹配的数据
问题描述
我有这个查询:
query ListFreightDriverTrucks($state: String! $tons: Float!) {
listFreightDrivers(filter: {
state: {
contains: $state
}
}) {
items {
name
city
state
trucks (filter: {
tons: {
eq: $tons
}
}) {
items {
id
brand
model
fuelType
fuelEfficiency
utilityPercentage
tons
axes
frontPhoto
truckBox {
type
width
height
depth
}
}
}
}
}
}
我得到了与$state
哈利斯科州匹配的数据作为响应。
{
"data": {
"listFreightDrivers": {
"items": [
{
"name": "Jaen Carlos",
"city": "Zapopan",
"state": "Jalisco",
"trucks": {
"items": []
}
},
{
"name": "Diey",
"city": "Zapopan",
"state": "Jalisco",
"trucks": {
"items": []
}
},
{
"name": "Roberto mendez",
"city": "Guadalajara",
"state": "Jalisco",
"trucks": {
"items": []
}
},
{
"name": "Engineering",
"city": "Zapopan",
"state": "Jalisco",
"trucks": {
"items": []
}
},
{
"name": "Roberto mendez",
"city": "Guadalajara",
"state": "Jalisco",
"trucks": {
"items": []
}
},
{
"name": "Andrés",
"city": "Zapopan",
"state": "Jalisco",
"trucks": {
"items": [
{
"id": "2b0cb78e-49c4-4229-8a71-60b350a5fc47",
"brand": "chevrolet",
"model": "xx",
"fuelType": "magna",
"fuelEfficiency": 12,
"utilityPercentage": 10,
"tons": 15,
"axes": 12,
"frontPhoto": "freight-driver/e9adf7fb-09c2-477e-9152-56fe4a71a96b/trucks/dlb0275xqna51.png",
"truckBox": {
"type": "Plataforma",
"width": 4,
"height": 4,
"depth": 4
}
}
]
}
}
]
}
}
}
如果你检查响应,有一些是这样的:
"trucks": {
"items": []
}
但我对那些不感兴趣,因为与$tons
最后一个不匹配。我怎样才能删除它们?
如果我需要制作一个 lambda,DynamoDB 查询的外观如何?
解决方案
我经常看到这个问题,这让我有点不安全,但 GraphQL 不应该以这种方式工作。你应该得到你所要求的,而不是“SQL 查询自己取得胜利”。
随便,
您可以通过过滤掉所有 trucks.items.length < 1 或其他内容,在解析器(req.vtl 文件)中解决此问题。请参阅此链接 Appsync & GraphQL: how to filter a list by nested value
请注意,这是一个非常慢的 DynamoDB 扫描操作(所有列表操作都是)。
AWS DynamoDB 具有相同的设计理念,即您大多数时候都知道您正在寻找的唯一键,并且只过滤少量项目。添加大量索引或组合键。
如果您想更新数据模型,推荐阅读: https ://docs.aws.amazon.com/amazondynamodb/latest/developerguide/best-practices.html
也许重新考虑你的 GraphQL 设计?我对卡车一无所知,但也许
- “位置有卡车有司机”而不是?或者
- “位置有司机有卡车”?
甚至两者都有!由于 GraphQL 为您提供了您想要的东西,Driver 可以包含 Truck,而 Truck 可以包含 Driver。
Location {
id: ID!
truck: [Truck]
driver: [Driver]
}
Truck {
id: ID!
driver: Driver!
}
Driver {
id: ID!
Truck: Truck!
}
Amplify 自动生成深度为 2,这样您的列表就不会永远循环下去,而且您可以不要求不需要的内容。这里有很多选择。
https://docs.amplify.aws/cli/graphql-transformer/dataaccess
如果你想让它成为一个 Lambda (@function),那么 dynamo 语法非常简单(并且几乎相同)。
要么扫描整个表https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB.html#scan-property ,要么创建一个查询的索引,然后过滤https://docs.aws。 amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB.html#query-property
最后但并非最不重要的
推荐阅读
- file - Ionic 4 文件插件从 assets 文件夹复制到默认目录
- php - 使用 php 通过 API 集成发送 SMS
- pandas - 根据所有列值 pandas 创建重复标志
- php - 计算数组中重复的空值
- python - 将 4D 转换为 2D 数组给了我:ValueError:形状(88,4)和(88,2)未对齐:4(dim 1)!= 88(dim 0)
- laravel - Vuex Axios CORS Block Access-control-allow-origin
- rust - 在迭代器特征中指定关联类型的生命周期
- c# - 如何对依赖的 cpde 进行单元测试
- postgresql - 在 PostGIS / PostgreSQL 中使用 st_transform 从质心坐标创建新列
- scala - 如何在 Http4s 中添加自定义错误响应?