如何在Dynamoose中更新DynamoDB表全局二级索引且保留原有索引
问题:Dynamoose更新Schema时保留原有全局二级索引的方法
问题背景
原有Dynamoose Schema定义如下:
const schema = new Schema( { id: { type: String, hashKey: true, required: true, }, name: { type: String, required: true, }, email: { type: String, index: { name: 'byEmail', type: 'global', rangeKey: 'id', }, }, }, { timestamps: true } );
需要新增一个以id为排序键的全局二级索引字段deleted,更新后的Schema:
const schema = new Schema( { id: { type: String, hashKey: true, required: true, }, name: { type: String, required: true, }, email: { type: String, index: { name: 'byEmail', type: 'global', rangeKey: 'id', }, }, deleted: { type: Number, index: { name: 'deletedIndex', rangeKey: 'id', type: 'global', }, default: 0, }, }, { timestamps: true } );
当前使用update: true初始化表时,Dynamoose会先删除所有原有索引再重建,最终仅保留新的deletedIndex,导致原有byEmail索引丢失。
解决方案
方法1:配置updateIndexes为追加模式
修改Table初始化配置,添加updateIndexes: "append"参数,该配置会让Dynamoose仅新增Schema中定义的新索引,不会删除原有已存在的索引:
const table = new Table(TableName, [TableModel], { initialize: false, update: true, updateIndexes: "append" // 核心配置:仅追加新索引,保留原有索引 }); table .initialize() .then(() => { console.log(`✅ ${TableName} 创建/更新成功`); }) .catch((error) => { logger.error(`💥:: ${error.name} - ${error.message}\n`, error); });
方法2:确保Schema保留所有需保留的索引定义
更新Schema时,必须完整保留原有email字段的索引配置。如果Schema中删除了旧索引的定义,Dynamoose会判定该索引需要被删除。只要Schema中保留了原有索引的配置,结合update: true和updateIndexes: "append",就能保证新旧索引同时存在。
方法3:分阶段手动操作(可选)
如果需要更精细的控制,可以分两步执行:
- 第一步:仅新增
deleted字段和对应的索引,保持原有Schema的索引配置不变,执行初始化操作创建新索引 - 第二步:确认新索引创建完成后,再进行其他Schema调整(如果有)
内容的提问来源于stack exchange,提问作者Kescript
相关产品推荐
相关产品推荐

