在dynamodb中的sort键的范围内查询

时间:2018-01-24 12:29:51

标签: c# amazon-web-services amazon-dynamodb

我正在尝试使用给定的分区键和排序键的范围来查询dynamodb表,但API不断抛出以下错误:

  

Amazon.DynamoDBv2.AmazonDynamoDBException   KeyConditionExpressions每个键只能包含一个条件

以下是用于创建请求的C#代码:

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 个答案:

答案 0 :(得分:1)

使用BETWEEN KeyConditionExpression运算符,如下所示:

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);