1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

AmplifyでDynamoDBのプライマリーキーを変更する

Posted at

Amplify Studioでモデルを作ろうとしたら、idがプライマリーキーとして登録されていて変更できないという経験をお持ちではないでしょうか?
image.png
ここでも、デバイスのテーブルを作ろうとしたのですが、各デバイスはDeviceIDを持っていて、このDeviceIDをプライマリーキーにしたいという場合の解決方法です。

解決: @primaryKeyを使いましょう

Amplifyのアプリケーションフォルダ配下 backend\api\APP_NAMEにあるschema.graphqlを編集します。

schema.graphql
# 変更前
type MetcomDevices @model @auth(rules: [{allow: public}]) {
  id: ID!
  DeviceID: String!
  Name: String
  AppID: String
  Latitude: Float
  Longitude: Float
  Accuracy: Float
  Calibration: Boolean
}

# 変更後
type MetcomDevices @model @auth(rules: [{allow: public}]) {
  DeviceID: String! @primaryKey
  Name: String
  AppID: String
  Latitude: Float
  Longitude: Float
  Accuracy: Float
  Calibration: Boolean
}

プライマリーキーに設定したいフィールドに@primaryKeyを付与するだけです。@keyで指定する方法はAmplify GraphQL Transformer v2以降使えなくなりました。

スキーマを書き換えた後、プッシュしたいのですが、プライマリーキーを変更すると、DyanamoDB上の該当テーブルの情報がクリアされるそうなので、それを明示的に指定して、プッシュします。--allow-destructive-graphql-schema-updatesオプションを追加するだけです。
amplify push --allow-destructive-graphql-schema-updates

確認

プライマリーキーが切り替わったことを確認するために、Amplify Studioを立ち上げてData modelingを見てみました。
image.png
残念ながら、Visual editorは使えなくなっていました。プライマリーキーが想定したものじゃなくなっているからという理由のようです。
でも、DyanamoDBのテーブル概要を見ると、ちゃんとidからDeviceIDに切り替わっていました。
image.png

image.png

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?