DynamoDB如何只按范围查询?

时间:2015-07-06 14:39:56

标签: amazon-dynamodb aws-sdk

我有一个包含哈希和范围主键的表。我需要通过eventDate和customerId进行查询。这是结构。 Hash是一个uniqueId格式,如UUID,range是customerId。我也有LSI与范围键eventDate。我想用param进行查询:

'KeyConditionExpression' => "customerId = :customer_id"

但我收到了一个错误:

Query condition missed key schema element: uniqueId

你可能会说我不应该使用无用的哈希,但我该怎么做呢?在此之前我尝试使用hash和range customerId,eventDate但我无法使用它们,因为它不能保证eventDate是唯一的。这意味着如果同时生成了三个事件,则只保存最后一个事件。

有没有办法将这种结构与dynamodb结合起来?

1 个答案:

答案 0 :(得分:1)

您可以执行以下操作之一:

  1. 将客户ID设为HashKey,将UUID设为RangeKey。然后,LSI将在CustomerID和EventDate上定义。您可以按如下方式在LSI上搜索表:

    // Using DynamoDBMapper in AWS SDK Java
    DynamoDBQueryExpression<YourClass> query = 
        new DynamoDBQueryExpression<YourClass>();
    YourClass hashKeyValues = new YourClass();
    hashKeyValues.setCustomerId(customerId);
    
    Map<String, Condition> rangeKeyConditions = 
        new HashMap<String, Condition>();
    rangeKeyConditions.put("EventDate", 
        new Condition()
            .withConditionalOperator(ConditionalOperator.EQ)
            .withAttributeValue(new AttributeValue(eventDate)));
    
    query.setHashKeyValues(hashKeyValues);
    query.setRangeKeyConditions(rangeKeyConditions);
    query.setIndexName(LSI_CUSTOMER_ID_EVENT_DATE);
    // Execute the query using DynamoDBMapper.
    
  2. 在CustomerID上创建全局二级索引(GSI)作为HashKey和EventDate作为GSI的RangeKey。

    // Using DynamoDBMapper in AWS SDK Java
    DynamoDBQueryExpression<YourClass> query = 
        new DynamoDBQueryExpression<YourClass>();
    YourClass hashKeyValues = new YourClass();
    hashKeyValues.setCustomerId(customerId);
    
    Map<String, Condition> rangeKeyConditions = 
        new HashMap<String, Condition>();
    rangeKeyConditions.put("EventDate", 
        new Condition()
            .withConditionalOperator(ConditionalOperator.EQ)
            .withAttributeValue(new AttributeValue(eventDate)));
    
    query.setHashKeyValues(hashKeyValues);
    query.setRangeKeyConditions(rangeKeyConditions);
    query.setIndexName(GSI_CUSTOMER_ID_EVENT_DATE);
    // Execute the query using DynamoDBMapper.
    
  3. 您可能知道使用GSI的费用,如果不是,您可能需要查看GSI documentation一次。

    HTH。