Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to query dynamoDB table by name using AWS Lambda

I have dynamoDB table,

Table name xx

Primary partition key id (Number)

Primary sort key name (String)

And I want to query it by name.

'use strict';
const AWS = require("aws-sdk");
const dynamodb = new AWS.DynamoDB();
const docClient = new AWS.DynamoDB.DocumentClient();

exports.handler = function(event, ctx, callback) {

    var params = {
          TableName: 'xx',

            KeyConditionExpression: "#name = :name",
                 ExpressionAttributeNames:{
            "#name": "name"
        },
                     ExpressionAttributeValues: {
            ":name":event.name
        }
    };

    docClient.query(params, function(err, data){
        if(err){
            callback(err, null);
        }else{
            callback(null, data);
        }
    });
}

but I got an error called :"Query condition missed key schema element:id:" how to deal with that?

like image 483
Piotr Kaliński Avatar asked Sep 11 '25 17:09

Piotr Kaliński


1 Answers

DynamoDB is a NoSQL Database so you can only query the primary key by default. You have a couple of options:

  • Create a Global Secondary Index and query against that (Link):

    "A global secondary index contains a selection of attributes from the base table, but they are organized by a primary key that is different from that of the table. The index key does not need to have any of the key attributes from the table; it doesn't even need to have the same key schema as a table."

  • Scan rather than Query:

    var params=  {
        TableName:'xx',
        ProjectionExpression:'name', // remove this string if you want to get not only 'name'
        FilterExpression:'name = :name',
        ExpressionAttributeValues:{ ":name" : event.name }
    };
    
    docClient.scan(params, function(err, data){
        if(err){
            callback(err, null);
        }else{
            callback(null, data);
       }
    });
    

If your tables isn't going to be huge Scan is the easier and cheaper way to do it (I believe Global Secondary Indicies have associated costs) but the 'correct' way to do it is with a Global Secondary Index.

like image 146
Simon Avatar answered Sep 13 '25 07:09

Simon