如何在 aws AppSync 中按 createdAt 和 updatedAt 排序和过滤?

Posted

技术标签:

【中文标题】如何在 aws AppSync 中按 createdAt 和 updatedAt 排序和过滤?【英文标题】:How to sort and filter by createdAt and updatedAt in aws AppSync? 【发布时间】:2021-07-16 21:33:20 【问题描述】:

我使用 AWS Amplify 创建了一个 GraphQL API。在 DynamoDB 中,createdAt 和 updatedAt 字段是自动创建的。我无法使用 Appsync 过滤此字段的值。我想使用 appsync 查询数据,过滤范围介于两个 createdAt 字段之间,但它没有出现在我的 appsync 查询架构中。

那么如何使用 createdAt 过滤器或排序进行查询?

这是一个 AWS-Amplify 特定的问题。这不是关于如何使用通用 GraphQL 来做到这一点。

【问题讨论】:

【参考方案1】:

我终于找到了解决办法。

您必须直接在 schema.graphql 上添加自动生成的字段“createdAt”和“updatedAt”

这样:

根据这个初始 schema.graphql:

type User @model(timestamps:  createdAt: "createdOn", updatedAt: "updatedOn" )

  id: String!
  username: String!
  firstName: String!
  lastName: String!
 

它会变成:

type User @model

  id: String!
  username: String!
  firstName: String!
  lastName: String!
  createdAt: AWSDateTime! #important to keep it to have filter with keys
  updatedAt: AWSDateTime! #important to keep it to have filter with keys
 

放大推送后,我们可以直接按日期获取物品,就这么简单:

query MyQuery 
  listUsers(filter: updatedAt: between: ["2021-04-29T16:02:21.285Z", "2021-05-29T16:02:21.285Z"]) 
    items 
      id
      lastName
    
  

【讨论】:

当我使用amplify mock 时,我无法使用createdAt 进行过滤操作。我需要推送才能使用它吗? 是的,您认为必须推送它来更新您的架构。但我暂时不使用 mock。

以上是关于如何在 aws AppSync 中按 createdAt 和 updatedAt 排序和过滤?的主要内容,如果未能解决你的问题,请参考以下文章