Search code examples
amazon-dynamodbdynamodb-queriesamazon-dynamodb-index

DynamoDB - Get Item by Global Secondary Index


I have an existing table which has 10 fields. Fields are like this:

AuthID, UserID, Age, Job, .etc

The table stores data of my users. "AuthID" is primary key and "UserID" is a Global Secondary Index.

When I get item by AuthID, everything is fine. But I can't get item by UserID. I tried GetItem, Query and Scan methods but I failed in all three method.

I need to be able to get data with these 3 methods I wrote below :

1 - Get user data by AuthID (It's already works fine)
2 - Get user data by UserID
3 - Get user data by AuthID and UserID both

AuthID and UserID is unique. Can someone point me right way as to what to do?


Solution

  • I have searched a lot in the documentation and found that if you need to get a single item even then you cant use the get or getItem method when using a global secondary index. One can use the query method. a sample of query method with global secondary index is

    let params = {
      TableName: "Users",
      IndexName: "your-index",
      ExpressionAttributeValues: {
        ":v1": "myid"
      }, 
      KeyConditionExpression: "my_partition_key_in_gsi = :v1", 
    };
     dynamodb.query(params, function(err, data) {
       if (err) console.log(err, err.stack); // an error occurred
       else     console.log(data);           // successful response
     });