1
votes

I'm trying to query a dynamodb table with a given partition key and a range for the sort key but the API keeps throwing back the following error:

Amazon.DynamoDBv2.AmazonDynamoDBException KeyConditionExpressions must only contain one condition per key

Here is the C# code for creating the request:

var partitionKey = 10;
var from = DateTime.NowUtc.AddDays(-1);
var to = DateTime.NowUtc;

var queryRequest = new QueryRequest
{
    TableName = _tableName,
    IndexName = "index",
    KeyConditionExpression = "#pkey = :v_pkey and #skey >= :v_from and #skey <= :v_to",
    ExpressionAttributeNames = {
        {"#pkey", "PartitionKey"},
        {"#skey", "SortKey"}
    },
    ExpressionAttributeValues = {
        {":v_pkey", new AttributeValue { N = partitionKey.ToString(CultureInfo.InvariantCulture) }},
        {":v_from", new AttributeValue { N = new DateTimeOffset(from).ToUnixTimeSeconds().ToString(CultureInfo.InvariantCulture) }},
        {":v_to", new AttributeValue { N = new DateTimeOffset(to).ToUnixTimeSeconds().ToString(CultureInfo.InvariantCulture) }}
    },
    ScanIndexForward = true
};

AmazonDynamoDBClient client = CreateClient();
var queryResponse = client.Query(queryRequest);
1

1 Answers

7
votes

Use the BETWEEN KeyConditionExpression operator like this:

var partitionKey = 10;
var from = DateTime.NowUtc.AddDays(-1);
var to = DateTime.NowUtc;

var queryRequest = new QueryRequest
{
    TableName = _tableName,
    IndexName = "index",
    KeyConditionExpression = "#pkey = :v_pkey AND #skey BETWEEN :v_from AND :v_to",
    ExpressionAttributeNames = {
        {"#pkey", "PartitionKey"},
        {"#skey", "SortKey"}
    },
    ExpressionAttributeValues = {
        {":v_pkey", new AttributeValue { N = partitionKey.ToString(CultureInfo.InvariantCulture) }},
        {":v_from", new AttributeValue { N = new DateTimeOffset(from).ToUnixTimeSeconds().ToString(CultureInfo.InvariantCulture) }},
        {":v_to", new AttributeValue { N = new DateTimeOffset(to).ToUnixTimeSeconds().ToString(CultureInfo.InvariantCulture) }}
    },
    ScanIndexForward = true
};

AmazonDynamoDBClient client = CreateClient();
var queryResponse = client.Query(queryRequest);