🐈
ElectroDB 使うときにハマったこと
TL;DR
-
attributes.field
で物理名(例:item-id
)をマッピングできる - マッピングした attribute を PK/SKで使うには、
indexes.{pk|sk}
のcomposite
とtemplate
が必要 -
composite
とtemplate
には attribute 名(例:itemId
) を設定する
はじめに
このような DynamoDB があるとします
{
"item-id": "abc123", # PK
"category": "electronics", # SK
"item-nm": "USB-C Hub"
}
項目がケバブケースだったり省略形だったりで、このまま扱いたくないです
そんなときは次のように field
でマッピングができます
attributes: {
itemId: {
type: "string",
required: true,
field: "item-id",
},
category: {
type: "string",
required: true,
},
itemName: {
type: "string",
field: "item-nm",
},
}
これだけであれば良かったのですが、これらを PK や SK に使いたいときは要注意です
マッピングした項目を PK/SK として使いたい
先ほどのようにマッピングした attribute を PK/SK として扱おうとしたのですが、ここがハマりポイントでした
indexes: {
primary: {
pk: {
field: "item-id",
composite: ["itemId"], // ← attribute名を使う
template: "${itemId}", // ← attribute名を使う
},
sk: {
field: "category",
composite: ["category"],
},
},
}
このように、composite
や template
にはマッピングした attribute名(例: itemId
)を指定する必要がありました。
はじめ、composite: ["item-id"]
や template: "${item-id}"
のように DynamoDB のフィールド名(物理名)を書いてしまい、それが原因でうまくいきませんでした...
参考
It may be the case that an index field is also an attribute. For example, if a table was created with a Primary Index partition key of accountId, and that same field is used to store the accountId value used by the application. The following are a few examples of how to model that schema with ElectroDB:
これ以外にも公式のドキュメント読んでみたところ、用語をこのように使い分けてそうです(おそらくですが)
- field: DynamoDBの物理項目
- attribute: ElectroDB の attributes で定義した項目
Discussion