u936293
u936293

Reputation: 16274

Query works at the console but not in code

My DynamoDB table alexas has this item with key "abc" as seen in the DynamoDB console below:

enter image description here

However, the following query returns no result:

const params = { TableName: "alexas",
  KeyConditionExpression: "deviceId = :deviceId",
  ExpressionAttributeValues: { ":deviceId": "abc"}
}
const docClient = new AWS.DynamoDB.DocumentClient();
docClient.query(params, (err, data) => {
  if (err) {
    console.error(err);
  } else {
    console.log(data);
  }
});

The above code returns null for err and in data:

{ Items: [], Count: 0, ScannedCount: 0 }

I am new to the DynamoDB style of expressions. Is there anything wrong with my code which I took from here.

If instead of query, I used the scan method and just have TableName in params, I get the items in my table. This confirms that I am performing the operations on the correct table that has data.

Upvotes: 5

Views: 1281

Answers (3)

u936293
u936293

Reputation: 16274

The query returned no data because the key value does not match.

The item's deviceId is the string "abc" and not abc. Note the extra quotation marks.

The item was inserted using the DynamoDB console's Create editor and there is no need to include "" if the value is already expected to be of type string.

Upvotes: 4

Ankit Deshpande
Ankit Deshpande

Reputation: 3604

Check QueryAPI

const params = { TableName: "alexas",
  KeyConditionExpression: "deviceId = :deviceId",
  ExpressionAttributeValues: {
     ":devideId":{
       S: "abc", // here
     }
  }
}
const docClient = new AWS.DynamoDB.DocumentClient();
docClient.query(params, (err, data) => {
  if (err) {
    console.error(err);
  } else {
    console.log(data);
  }
});

ExpressionAttributeValues needs to be passed in a different manner.

Update: Try using Exp attribute names, (I'm not sure if this will make a difference)

var params = {
     TableName: "alexas",
     KeyConditionExpression: "#d = :dId",
     ExpressionAttributeNames:{
          "#d": "email"
     },
     ExpressionAttributeValues: {
           ":dId": "abc"
     }
};

Upvotes: 0

Nadav Har'El
Nadav Har'El

Reputation: 13801

DynamoDB's Scan operation doesn't take a KeyConditionExpression - only the Query operation takes this parameter. Scan always scans the entire table, and has a FilterExpression to post-filter these results (however please note that you still pay for scanning the entire table).

For example, here is the official documentation of Scan: https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Scan.html

Upvotes: 0

Related Questions