【问题标题】:How to update item by Composite Primary Key in Dynamodb如何通过 Dynamodb 中的复合主键更新项目
【发布时间】:2015-11-05 07:48:45
【问题描述】:

我有一张叫朋友的桌子:

Friend 1 | Friend 2 | Status

Friend 1 是我的 HASH 属性,Friend 2 是我的 range 属性。

我想更新一个项目的状态属性,其中朋友 1 = 'Bob' 和朋友 2 = 'Joe'。阅读http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/JavaDocumentAPICRUDExample.html 上的文档,我只能看到如何通过 1 个键更新项目,如何包含另一个键?

【问题讨论】:

    标签: amazon-web-services amazon-dynamodb


    【解决方案1】:

    给你:

    DynamoDBQueryExpression<Reply> queryExpression = new DynamoDBQueryExpression<Reply>()
                .withKeyConditionExpression("Id = :val1 and ReplyDateTime > :val2")
                .withExpressionAttributeValues(
    ...
    

    其中 Id 是哈希键,ReplyDateTime 是范围键。

    参考: http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBMapper.QueryScanExample.html

    【讨论】:

      【解决方案2】:

      我正在编写示例,您可以在其中更新单个表中的多个项目。我有主键作为 id 和范围键作为日期时间。 实际上 dynamodb 中没有可用的功能,所以我在这里做的是首先使用我想要更新的哈希键和范围键查询所有变量。一旦所有数据都存储在 List 中,然后使用它的 hash key 和 rangekey 加载数据,并使用 set 更改或更新字段并保存它。 由于我在哈希键中进行编辑,因此哈希键原始将在那里,我们需要将其删除。如果您需要在下一个属性中更新,则无需。我没有添加自己编写的删除代码。如果您有混淆,您可以查询带有哈希键的条目将仍然存在,并且将添加带有新哈希键的新条目。 代码如下:

      public static void main(String[] args) {
          AmazonDynamoDBClient client = new AmazonDynamoDBClient();
          DynamoDBMapper mapper = new DynamoDBMapper(client);
          client.setEndpoint("http://localhost:8000/");
          String fromDate = "2016-01-13";
          String toDate = "2016-02-05";
          User user = new User();
          user.setId("YourHashKey");
          LocalDate frmdate = LocalDate.parse(fromDate, DateTimeFormatter.ISO_LOCAL_DATE);
          LocalDate todate = LocalDate.parse(toDate, DateTimeFormatter.ISO_LOCAL_DATE);
          LocalDateTime startfrm = frmdate.atStartOfDay();
          LocalDateTime endto = todate.atTime(23, 59, 59);
          Condition rangeCondition = new Condition().withComparisonOperator(ComparisonOperator.BETWEEN.toString()).withAttributeValueList(new AttributeValue().withS(startfrm.toString()), new AttributeValue().withS(endto.toString()));
          DynamoDBQueryExpression<User> queryExpression = new DynamoDBQueryExpression<User>().withHashKeyValues(user).withRangeKeyCondition("DATETIME", rangeCondition);
          List<User> latestReplies = mapper.query(User.class, queryExpression);
          for (User in : latestReplies) {
              System.out.println(" Hashid: " + in.getId() + " DateTime: " + in.getDATETIME() + "location:" + in.getLOCID());
              User ma = mapper.load(User.class, in.getId(), in.getDATETIME());
              ma.setLOCID("Ohelig");
              mapper.save(ma);
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-16
        • 1970-01-01
        • 2021-02-23
        • 2013-12-19
        • 1970-01-01
        • 2019-01-08
        相关资源
        最近更新 更多