【问题标题】:Query within a range on sort key within dynamodb在dynamodb中的排序键范围内查询
【发布时间】:2018-01-24 12:29:51
【问题描述】:

我正在尝试使用给定的分区键和排序键的范围查询 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);

【问题讨论】:

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


    【解决方案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);
    

    【讨论】:

    • 很好,完美的作品也在文档的部门中找到了。奇怪的是,我只是期望它会改变自己,而不必如此冗长和明确。
    • BETWEEN 在两端都包含。我的用例需要像 #skey &gt;= :v_min AND #skey &lt; :v_max 这样的条件。我必须使用 BETWEEN 进行查询,然后在 DynamoDB 返回后丢弃具有 #skey = :v_max 的结果。
    猜你喜欢
    • 1970-01-01
    • 2016-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多