Search code examples
aws-lambdaamazon-dynamodb

How can I query dynamodb to return items where a numeric secondary key is smaller than a supplied value?


I have a dynamodb table called posts. It has a secondary index 'tsProcess' that is a number.

In a lambda function I want to query for all items where tsProcess is less than a value, in the example below I am trying to find all items where tsProcess is less than 1600.

Here is the code:

ex = {
    TableName: "posts",
    IndexName: "tsProcess-index",
    KeyConditionExpression: "tsProcess < :t1",
    ExpressionAttributeValues: {
        ":t1": 1600,
    },
};
command = new QueryCommand(ex);

This gets the response:

"errorType": "ValidationException",
"errorMessage": "Query key condition not supported",

Is it possible to run a query in this way? How do I need to change the expression to accomplish it?


Solution

  • When you use Query, you must also provide the partition key value.

    KeyConditionExpression: "myPk= 1 AND tsProcess < :t1"
    

    https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Query.html

    If the partition key is unknown, you will have to use Scan with a Filter expression, which reads every item in the table.


    If your index has a partition key of tsProcess then you must provide the equality = operator on it, you cannot do a range condition on a partition key, only on the sort key.