Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BatchGetItem or Query DynamoDb - Query by Range

I have a table called User. It has a Hash key of User Id and a Range key of Organization Id.

How can I return all of the Users that have the Organization Id of "3"

(This is a Lambda function, by the way)

This code is giving me an error:

console.log('Loading event');
var AWS = require('aws-sdk');
var dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'});

exports.handler = function(event, context) {
dynamodb.listTables(function(err, data) {
});

var params = {
    "TableName": "PoliceUser",
     "Key":
        {"User Id"   : {"S":event.objectId}, "Organization Id" : {"S": event.organizationId}
    },
   "ProjectionExpression": "#firstName, #lastName, #longitude, #latitude, #organizationName",
   "ExpressionAttributeNames" : {"#firstName": "First Name", "#lastName": "Last Name", "#longitude": "Longitude", "#latitude": "Latitude", "#organizationName": "Organization"},
   "ConsistentRead"    : true
  }

   dynamodb.BatchGetItem(params, function(err, data)
{
    if (err) {
        context.fail('error','Error updating item: '+err);
        console.log(err);
    }
  else  
  {
      //  console.log('great success: '+JSON.stringify(data, null, '  '));
       console.log(data);   
        context.succeed( data);
    }

    // successful response


});
};
like image 923
Rupert Avatar asked Jul 17 '26 07:07

Rupert


1 Answers

DynamoDB provides a few ways to query items (assuming your table has a hash key and range key):

  • Getting an individual item by hash key + range key
  • Querying all of the items for a specific hash key
  • Scanning the entire table

With a hash key of "User Id" and range key of "Organization Id" you can only query for all of the organizations that an individual user is associated with.

It sounds like you want the opposite, all of the users that belong to an organization.


One option would be to swap your hash key and range key. Before you do that make sure that this actually makes sense for your use case.


Alternatively you could add a Global Secondary Index to your table where the hash key is "Organization Id" and range key is "User Id" while leaving the existing hash/range key as they currently exist. You would then be able to use this index to return all users that have the Organization Id of "3".

I'd recommend you read up on GSIs some before creating one. They are very useful, but can be tricky. The GSI is technically a physical copy of the data so you need to decide which columns you want to project (what columns you can read when using an index). Also GSIs are asynchronously updated so they are eventually consistent. They also have their own provisioned read/write throughput and can theoretically impact the maximum throughput you can achieve on a table depending on your access patterns.

like image 150
JaredHatfield Avatar answered Jul 19 '26 01:07

JaredHatfield