Marsstar
Marsstar

Reputation: 197

How to query a table in DynamoDB using KeyConditions and using AWS-JS-SDK

I am trying to query from a dummy table I created manually.

Table name: myTable

Primary partition key: id (String)

Primary sort key: ts (Number)


The table has the following items:

id | ts | humidity | temperature

outTopic | 1233 | 50 | 30

outTopic | 1234 | 51 | 31

outTopic | 1235 | 52 | 32


I am able to query the table through the AWS management console, but not using the AWS Javascript SDK.

Question: I would like to query only items with values of timestamps less and equal than 1234.

But when I run my code using Node.js:

let docClient = new AWS.DynamoDB.DocumentClient();
 
var params_query = {
        TableName: "myTable",
        KeyConditionExpression: '#id = :iottopic and #ts <= :time_val',
        ExpressionAttributeNames: {
            "#id": "id",
            "#ts": "ts"
        },
        ExpressionAttributeValues: {
            ":iottopic": {"S": "outTopic"},
            ":time_val": {"N": "1234"}
        }
};
 
docClient.query(params_query, function (err, data) {
        if (err) {
            console.log("error - " + JSON.stringify(err, null, 2));
        }
        else {
            console.log("success - " + JSON.stringify(data, null, 2));
        }
})

I get the following error:

Invalid KeyConditionExpression: Incorrect operand type for operator or function; operator or function: <=, operand type: M

I get the two items as expected when I run the equivalent command using the AWS CLI:

aws dynamodb query \
    --table-name myTable \
    --key-condition-expression "id = :iottopic AND ts <= :time_val" \
    --expression-attribute-values \ 
    '{":iottopic": {"S": "outTopic" },":time_val": {"N": "1234"}}'

Upvotes: 2

Views: 4205

Answers (1)

Marsstar
Marsstar

Reputation: 197

The arguments for ExpressionAttributeValues should be like this:

ExpressionAttributeValues: {
    ":iottopic": "outTopic",
    ":time_val": 1234
}

The attribute types are omitted.

Upvotes: 1

Related Questions