0
votes

I have a table in Dynamodb and I'm trying to get an item (using docClient.get) by naming a Global Secondary Index but I'm getting the error:

The provided key element does not match the schema

And here's my query:

docClient
    .get({
      TableName: 'table',,
      IndexName: 'gsi_table',
      Key: { primary_key }
    })

But then I looked at the get documentation and it does not have an IndexName property. So I thought maybe I should name the GSI instead of the table name:

docClient
    .get({
      TableName: 'gsi_table',
      Key: { primary_key }
    })

But then I faced:

Requested resource not found

which means gsi_table is not recognized as a global table. So my question is, having the list of operations:

  • batchGet
  • batchWrite
  • createSet
  • delete
  • get
  • put
  • query
  • scan
  • update

which ones support GSI and LSI? And also, if you want to retrieve one specific item using a GSI, which operation should you use? If I use query, am I actually doing things as fast/cheap as possible?

1

1 Answers

2
votes

Secondary indexes are for Query and Scan operations only. So, if you must use a global (or local) secondary index, then Query would be faster than Scan, of course.

To access your "single" item, you can use data.Items[0]. For example:

const params = {
    TableName: "TABLE_NAME",
    IndexName: "INDEX_NAME",
    KeyConditionExpression: "INDEX_KEY = :k",
    ExpressionAttributeValues: {
        ":k": some_value
    }
};

docClient.query(params, (err, data) => {
    if (err) {
        console.log(err);
    } else {
        const myItem = data.Items[0];
    }
});