Question:
I’m attempting to read all values in a DynamoDB table above a certain value. I have the primary partition key set to a Number called Project_ID.
I am running a query to see all values above a certain ID – mostly to test out functionality, however I am getting an error when running the code.
The code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
var params = { TableName : document.getElementById("tableName").value, KeyConditionExpression: "Project_ID > :v1", "ExpressionAttributeValues": { ":v1": {"N": "0"} } }; docClient.query(params, function(err, data) { if (err) { document.getElementById('textarea').innerHTML += "Unable to query. Error: " + "\n" + JSON.stringify(err, undefined, 2); } else { data.Items.forEach(function(project) { //JSON.stringify(project); document.getElementById('textarea').innerHTML += "\n" + project.Project_Name + ": " + project.Project_Ref; }); } }); |
The output
1 2 3 4 5 |
`Unable to query. Error: { "message": "Invalid KeyConditionExpression: Incorrect operand type for operator or function; operator or function: >, operand type: M", "code": "ValidationException", "time": "2017-04-28T10:52:31.381Z",` |
Answer:
In KeyConditionExpression of Query API, the partition key can have only equality operator. The sort key can have multiple operators.
The condition must perform an equality test on a single partition key
value. The condition can also perform one of several comparison tests
on a single sort key value.
Example (sort key):-
sortKeyName < :sortkeyval – true if the sort key value is less than
:sortkeyval.sortKeyName <= :sortkeyval – true if the sort key value is less than
or equal to :sortkeyval.
You may need to use Scan (with FilterExpression) or BatchGetItem API if you wanted to get multiple items based on some criteria.
Note:-
Scan API will scan the whole table which is costly and inefficient.