amazon-dynamodbsecondary-indexesdynamoose

How do I update global secondary indexes and keys in dynamodb table from my dynamodb schema update?


I have a 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 }
);

And I want to update this schema by adding another field as a global index and id as a range key.


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 }
);

How do I make dynamoose update my indexes without having to delete already existing indexes and end up creating just one index?

After updating this schema, I initialized my table adding the update property with a value of true, My table ends up deleting all index before trying to re-create them and at the end only one index will be created.


const table = new Table(TableName, [TableModel], {
  initialize: false,
  update: true,
});

table
  .initialize()
  .then(() => {
    console.log(`✅ ${TableName} created successfully`);
  })
  .catch((error) => {
    logger.error(`💥:: ${error.name} - ${error.message}\n`, error);
  });

This is what I'm doing currently and it's creating issues for my tables


Solution

  • DynamoDB prohibits the ability to change a table or index keys. So any change to a key in your GSI from Dynamoose warrants a delete index and a create index action.