Skip to main content

DynamoDb part 1

1)Create a table :


const createTableParams = {

  TableName: 'Orders',

  KeySchema: [

    { AttributeName: 'orderId', KeyType: 'HASH' }, // Partition key

    { AttributeName: 'orderTimestamp', KeyType: 'RANGE' } // Sort key

  ],

  AttributeDefinitions: [

    { AttributeName: 'orderId', AttributeType: 'S' },

    { AttributeName: 'orderTimestamp', AttributeType: 'S' },

    { AttributeName: 'customerId', AttributeType: 'S' }, // Attribute for GSI

    { AttributeName: 'status', AttributeType: 'S' } // Attribute for GSI

  ],

  ProvisionedThroughput: {

    ReadCapacityUnits: 5,

    WriteCapacityUnits: 5

  },

  GlobalSecondaryIndexes: [

    {

      IndexName: 'CustomerIdIndex',

      KeySchema: [

        { AttributeName: 'customerId', KeyType: 'HASH' },

        { AttributeName: 'orderTimestamp', KeyType: 'RANGE' }

      ],

      Projection: { ProjectionType: 'ALL' },

      ProvisionedThroughput: {

        ReadCapacityUnits: 5,

        WriteCapacityUnits: 5

      }

    },

    {

      IndexName: 'OrderStatusIndex',

      KeySchema: [

        { AttributeName: 'status', KeyType: 'HASH' },

        { AttributeName: 'orderTimestamp', KeyType: 'RANGE' }

      ],

      Projection: { ProjectionType: 'ALL' },

      ProvisionedThroughput: {

        ReadCapacityUnits: 5,

        WriteCapacityUnits: 5

      }

    }

  ]

};


dynamodb.createTable(createTableParams, function(err, data) {

  if (err) {

    console.error('Error creating table:', err);

  } else {

    console.log('Table created:', data);

  }

});


2)Add data:

const itemsToAdd = 

  {

    orderId: 'order1',

    orderTimestamp: '2023-08-09T10:00:00Z',

    customerId: 'customer123',

    status: 'pending'

    // Add other attributes as needed

  };

async function addItemToTable(item) {
  const params = {
    TableName: tableName,
    Item: item
  };

  
    await dynamodb.put(params).promise();
}
addItemToTable(itemsToAdd)

Comments