如何为AWS Amplify DynamoDB API手动设置分区键
解决方案
1. 调整GraphQL Schema配置
该问题的核心是Amplify对@model类型下默认的ID类型主键,默认开启了自动生成逻辑,即使用户传入自定义id也会被覆盖。需要显式修改Schema关闭该默认规则:
默认的Schema写法(自动生成id):
type UserProfile @model { id: ID! # 其他业务字段 }
修改后的Schema写法(支持自定义id):
type UserProfile @model { # 显式声明为主键,关闭默认自动生成逻辑 id: ID! @primaryKey # 其他业务字段,比如用户名、邮箱等 username: String! email: String }
如果需要同时支持自动生成和自定义传入(不传id时系统自动生成,传了就用自定义值),可以用如下写法:
type UserProfile @model { id: ID! @primaryKey @default(value: "auto()") # 其他业务字段 }
2. 推送配置更新并生成本地代码
修改Schema后执行以下命令生效:
- 推送Schema更新到云端:
amplify push api - 更新本地GraphQL语句和类型定义:
amplify codegen
3. 前端调用时传入自定义id
以React Native环境的Amplify v6为例,创建条目时直接在input参数中传入id即可:
import { generateClient } from 'aws-amplify/api'; import { createUserProfile } from './graphql/mutations'; const client = generateClient(); // 示例:自定义id可以用Cognito返回的用户sub,方便后续直接对应用户身份 const customUserId = "你需要设置的自定义id值"; const createUser = async () => { const res = await client.graphql({ query: createUserProfile, variables: { input: { id: customUserId, username: "测试用户", email: "test@example.com" } } }); // 返回结果的id即为你传入的自定义值 console.log('创建的用户资料id:', res.data.createUserProfile.id); }
常见注意事项
- 自定义id必须全局唯一,重复的主键会导致创建操作抛出冲突错误
- 之前已经生成的旧数据不受Schema修改影响,仅新创建的条目支持自定义id
- 如果调用时提示input中不存在id字段,确认你已经执行了
amplify codegen更新本地类型定义
内容的提问来源于stack exchange,提问作者xyzfeasd
相关产品推荐
相关产品推荐

