Home > other >  Return Multiple Records AWS Lambda Function Query
Return Multiple Records AWS Lambda Function Query

Time:12-31

I am learning lambda functions in AWS and I am trying to figure out how I can query a dynamodb table with my pk and sk to return all records that match. I've been able to return a single record but I haven't figured out how to return an entire list of records that I can update.

Is this possible with a lambda function? Node.js is what I've been using?

CodePudding user response:

you can return JSON as string and parse it at client end. implementation may vary depends on programing language you are using and it's calling code/app.

If you plan to invoke the Lambda function synchronously (using the RequestResponse invocation type), you can return the output of your function using any of the supported data types. For example, if you use a Lambda function as a mobile application backend, you are invoking it synchronously. Your output data type will be serialized into JSON.

The output type can be an object or void. The runtime serializes return values into text. If the output is an object with fields, the runtime serializes it into a JSON document. If it's a type that wraps a primitive value, the runtime returns a text representation of that value.

some sample java code:

public class HandlerString implements RequestHandler<String, Integer>{
  Gson gson = new GsonBuilder().setPrettyPrinting().create();
  @Override
  public Integer handleRequest(String event, Context context)
  {
    LambdaLogger logger = context.getLogger();
    // process event
    logger.log("EVENT: "   gson.toJson(event));
    logger.log("EVENT TYPE: "   event.getClass().toString());
    return context.getRemainingTimeInMillis() ;
  }
}

Python

The following example shows a function called lambda_handler that uses the python3.8 Lambda runtime. The function uses event data passed by Lambda at runtime. It parses the environment variable in AWS_REGION returned in the JSON response.

def lambda_handler(event, context):
    json_region = os.environ['AWS_REGION']
    return {
        "statusCode": 200,
        "headers": {
            "Content-Type": "application/json"
        },
        "body": json.dumps({
            "Region ": json_region
        })
    }

CodePudding user response:

how I can query a dynamodb table with my pk and sk to return all records that match.

My answer would be describing the use cases for pk and sk so that you can use this principle.

  • Inside a dynamodbDB you can have either a single Partition key which should be unique ( for a single PK) or a combination of the Partition key and sort key.

According to docs (for a combination of Pk and sk) -> DynamoDB uses the partition key value as input to an internal hash function. The output from the hash function determines the partition (physical storage internal to DynamoDB) in which the item will be stored. All items with the same partition key value are stored together, in sorted order by sort key value. In a table that has a partition key and a sort key, it's possible for multiple items to have the same partition key value. However, those items must have different sort key values.

for such composite key table design SO you can have scenarios:-

  • find a single record for pk and sk using get ( combination of pk and sk would be unique)
  • find multiple records for the same pk using a query.

For example there is table with name as pk and serial no as sort key. in such a case you can query mutiple records with name 'abc'.

i am using javascript.

const paramsForQuery = {
    TableName: tableName,
    KeyConditionExpression: 'name=:name',
    ExpressionAttributeValues: {
      ':ename': 'abc,
    },
  };
const dynamoDbQueryResults = await dynamoDb
      .query(paramsForQuery)
      .promise();

query operation official docs https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Query.html

  • Related