Home > Enterprise >  How to create an item with an index in DynamoDB?
How to create an item with an index in DynamoDB?

Time:02-03

I have been looking everywhere on AWS docs for any information on this and can find absolutely none. The only answer I keep getting everywhere I look is how to query or scan using a secondary index, on already-indexed data. But how do you add a value to the index-attribute of an item in the first place? I am using AWS SDK for JavaScript so JS-specific info would be most helpful, but any info on this would be so much better than what AWS has provided.

I tried to add an item with params like the following, where I simply used the names of indexes as attributes (date and timestamp):

const params = { TableName: 'Posts_Table', Item: { 'username' : user, 'image_id' : uuid(), 'date' : date, 'timestamp' : timestamp } }

But what ended up happening is date and timestamp were simply added as normal attributes that aren't able to be queried.

CodePudding user response:

You've got some fundamental misunderstanding going on. You don't give enough code or examples for me to guess what you're really attempting. For example, I don't know what your table's keys are. So here's a primer:

You only write items to the base table (never directly to an index). Items can have a variety of attributes. Each item must have unique key attributes in the base table.

You can create a GSI against the table, including after the table has data. When constructing the GSI you select what its key attributes will be.

When you want to use the GSI you must specify it in the query as your Scan or Query target.

Are you trying to write to the index? You can't.

Are you trying to query the index by pointing at the base table? You can't.

Are you trying to write an item to the base table without specifying its primary keys? You can't.

CodePudding user response:

How to create an item with an index in DynamoDB?

You can not create an item without an index in DynamoDB.

When you create a table, you specify the Primary Key which is your index.

When you add an item, you have to provide the Primary Key.

You can also make use of Global Secondary Indexes which technically create a new table with that index under the hood.

But what ended up happening is date and timestamp were simply added as normal attributes that aren't able to be queried.

If you want to be able to query an attribute, that attribute has to be a Primary Key (Partition or Composite) or a Global Secondary Index.

  • Related