【问题标题】:DynamoDB how to query only by range?DynamoDB如何仅按范围查询?
【发布时间】:2015-07-06 14:39:55
【问题描述】:

我有一个带有散列和范围主键的表。我需要通过 eventDate 和 customerId 查询。这是结构。 Hash 是一个类似于 UUID 格式的 uniqueId,range 是一个 customerId。我也有范围键 eventDate 的 LSI。我想用参数进行查询:

'KeyConditionExpression' => "customerId = :customer_id"

但我得到了一个错误:

Query condition missed key schema element: uniqueId

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

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

【问题讨论】:

    标签: amazon-dynamodb aws-sdk


    【解决方案1】:

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

    1. 将客户 ID 设为 HashKey,将 UUID 设为 RangeKey。然后,将在 CustomerID 和 EventDate 上定义 LSI。您可以在 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) 作为 GSI 的 HashKey 和 EventDate 作为 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.
      

    您可能知道使用 GSI 的成本,如果没有,您可能需要检查一次 GSI documentation

    HTH。

    【讨论】:

      猜你喜欢
      • 2017-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-21
      • 2018-05-04
      • 2016-09-05
      • 1970-01-01
      相关资源
      最近更新 更多