4

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?

0

1 Answer 1

9

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Actually, this is the only answer that leads to solution. Maybe I'm blind, but I found zero information about query working only with primary keys. Big, very big thanks for this.
Just a quick note, you have to be careful when using scan. AWS docs recommend using query instead of scan. See for more details docs.aws.amazon.com/amazondynamodb/latest/developerguide/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.