【问题标题】:GraphQL: Sorted Query Based on User AttributeGraphQL:基于用户属性的排序查询
【发布时间】:2020-02-10 00:17:55
【问题描述】:

我刚刚使用 AWS Amplify、DynamoDB 和 GraphQL 在我的 iOS 应用程序中实现了分页。我想做的是根据用户的分数从高到低查询用户。为此,我需要在拨打电话时对查询进行排序。如何根据用户的分数进行排序查询?

下面是我的用户表

type User @model @key(fields: ["username"]) {
  name: String
  email: String!
  username: String!
  dateOfBirth: String
  university: String!
  phoneNumber: String!
  biography: String
  score: Int!
  deviceToken: String
  endpointArn: String
}

【问题讨论】:

    标签: sorting graphql amazon-dynamodb aws-amplify aws-appsync


    【解决方案1】:

    这是索引的一个用例。

    就如何实现该数据访问模式而言,当您使用@key 指令时,Amplify 会为您创建一个全局二级索引。在这种情况下,由于您只对高分感兴趣,您可以通过将以下指令添加到您的用户模型来在分数字段上创建另一个 GSI:

    @key(name: "UsersByScore", fields: ["username","score"], queryField: "UsersByScore")

    然后,在指定限制 n 和排序方向的情况下,使用 Amplify 生成的 UsersByScore 查询来查询得分最高(或最低)的 n 用户。

    【讨论】:

    • 感谢您的回答。 OP可以尝试一下,因为它应该可以实现他们想要的。
    • 嗨@mparis 我在 Amplify CLI 和 SDK Github 问题页面上很活跃。任何有 Amplify 查询的人也应该检查这些问题页面(或者有人应该将其作为一个项目,通过 Github 将已解决的问题移植到 StackOverflow 答案)。 github.com/aws-amplify/amplify-cli/issues
    • @jkeys,我认为你的回答有问题:首先,字段应该是 ["username", "score"]。其次,使用你建议放大的@key会引发错误:Invalid @key "UsersByScore". You may not create a @key where the first field in 'fields' is the same as that of the primary @key unless the primary @key has multiple 'fields'. You cannot have a local secondary index without a sort key in the primary index.
    • @Valerio 你对语法错误的看法是正确的。但我不知道 GraphQL 转换器不支持将排序字段添加到新索引。
    • @jkeys 我在 amplify-cli repo 中开始了一个问题来解决这个特定的情况。我偶然发现了你的答案,因为我正在寻找这个确切的问题。 github.com/aws-amplify/amplify-cli/issues/2643
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-20
    • 1970-01-01
    • 2016-10-16
    相关资源
    最近更新 更多