DynamoDB 中条件写入的日期时间比较

2024-05-11

我目前正在使用 DynamoDB。如果该记录的日期早于新记录日期字段,我想使用条件写入来更新该记录。

有没有办法比较条件写入的 DateTime 类型?或者目前仅适用于整数、字符串和流?

Thanks.


既然你提到你正在使用ISO-8601 http://en.wikipedia.org/wiki/ISO_8601String数据类型,很容易使用比较运算符(<, <=等)在你的条件表达式 http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.SpecifyingConditions.html因为中描述的字典顺序这个答案 https://stackoverflow.com/a/5098252/627727.

这是一个简单的示例,我使用 Java 8 的时间并针对 DynamoDB Local 运行它:

import com.google.common.collect.ImmutableMap;

import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
import com.amazonaws.services.dynamodbv2.document.Item;
import com.amazonaws.services.dynamodbv2.document.Table;
import com.amazonaws.services.dynamodbv2.document.spec.UpdateItemSpec;
import com.amazonaws.services.dynamodbv2.model.AttributeDefinition;
import com.amazonaws.services.dynamodbv2.model.ConditionalCheckFailedException;
import com.amazonaws.services.dynamodbv2.model.CreateTableRequest;
import com.amazonaws.services.dynamodbv2.model.KeySchemaElement;
import com.amazonaws.services.dynamodbv2.model.KeyType;
import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput;
import com.amazonaws.services.dynamodbv2.model.ScalarAttributeType;
import com.amazonaws.services.dynamodbv2.util.Tables;

import java.time.Instant;
import java.time.temporal.ChronoUnit;

public class DynamoDBStackoverflow {

    public static final String TABLE_NAME = "exampleTable";
    private static final String HASH_KEY = "hashAttributeName";

    public static void main(String[] args) {

        AWSCredentials awsCredentials = new BasicAWSCredentials("key", "secret");
        AmazonDynamoDB client = new AmazonDynamoDBClient(awsCredentials);
        client.setEndpoint("http://localhost:4000");
        DynamoDB dynamoDB = new DynamoDB(client);

        if (Tables.doesTableExist(client, TABLE_NAME)) {
            client.deleteTable(TABLE_NAME);
        }

        final CreateTableRequest createTableRequest = new CreateTableRequest()
            .withTableName(TABLE_NAME)
            .withKeySchema(new KeySchemaElement(HASH_KEY, KeyType.HASH))
            .withAttributeDefinitions(new AttributeDefinition(HASH_KEY, ScalarAttributeType.S))
            .withProvisionedThroughput(new ProvisionedThroughput(15L, 15L));
        final Table table = dynamoDB.createTable(createTableRequest);

        final Instant now = Instant.now();
        final Instant before = now.minus(10, ChronoUnit.MINUTES).truncatedTo(ChronoUnit.MINUTES);
        final Instant after = now.plus(10, ChronoUnit.MINUTES);
        System.out.println("Before: " + before.toString());
        System.out.println("Now: " + now.toString());
        System.out.println("After: " + after.toString());

        table.putItem(new Item().withPrimaryKey(HASH_KEY, "1")
                          .withString("dateField", before.toString()));
        table.putItem(new Item().withPrimaryKey(HASH_KEY, "2")
                          .withString("dateField", now.toString()));
        System.out.println("put items");
        table.scan().forEach(System.out::println);

        UpdateItemSpec updateItemSpec = new UpdateItemSpec().withPrimaryKey(HASH_KEY, "1")
            .withConditionExpression("dateField < :beforeDate")
            .withValueMap(ImmutableMap.of(":beforeDate", before.toString()))
            .withUpdateExpression("SET dateField = :beforeDate");

        try {
            table.updateItem(updateItemSpec);
            throw new RuntimeException();
        } catch (ConditionalCheckFailedException ccfe) {
            System.out.println("expected conditional write with < to fail when they are equal");
        }

        updateItemSpec = new UpdateItemSpec().withPrimaryKey(HASH_KEY, "2")
            .withConditionExpression("dateField < :beforeDate")
            .withValueMap(ImmutableMap.of(":beforeDate", before.toString()))
            .withUpdateExpression("SET dateField = :beforeDate");

        try {
            table.updateItem(updateItemSpec);
            throw new RuntimeException();
        } catch (ConditionalCheckFailedException ccfe) {
            System.out.println("expected conditional write with < to fail when new is before");
        }

        updateItemSpec = new UpdateItemSpec().withPrimaryKey(HASH_KEY, "1")
            .withConditionExpression("dateField <= :beforeDate")
            .withValueMap(ImmutableMap.of(":beforeDate", before.toString()))
            .withUpdateExpression("SET dateField = :beforeDate");

        try {
            table.updateItem(updateItemSpec);
        } catch (ConditionalCheckFailedException ccfe) {
            System.out.println("should not happen");
            throw new RuntimeException();
        }

        updateItemSpec = new UpdateItemSpec().withPrimaryKey(HASH_KEY, "2")
            .withConditionExpression("dateField <= :afterDate")
            .withValueMap(ImmutableMap.of(":afterDate", after.toString()))
            .withUpdateExpression("SET dateField = :afterDate");
        try {
            table.updateItem(updateItemSpec);
        } catch (ConditionalCheckFailedException ccfe) {
            System.out.println("should not happen");
            throw new RuntimeException();
        }

        System.out.println();
        System.out.println("after all updates");
        table.scan().forEach(System.out::println);
    }
}

和输出:

Before: 2015-06-08T15:57:00Z
Now: 2015-06-08T16:07:08.893Z
After: 2015-06-08T16:17:08.893Z
put items
{ Item: {hashAttributeName=1, dateField=2015-06-08T15:57:00Z} }
{ Item: {hashAttributeName=2, dateField=2015-06-08T16:07:08.893Z} }
expected conditional write with < to fail when they are equal
expected conditional write with < to fail when new is before

after all updates
{ Item: {hashAttributeName=1, dateField=2015-06-08T15:57:00Z} }
{ Item: {hashAttributeName=2, dateField=2015-06-08T16:17:08.893Z} }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

DynamoDB 中条件写入的日期时间比较 的相关文章

随机推荐

  • 如何在 Angular 模板中嵌入 GitHub gist?

    角度忽略script其模板中包含标签 但加载 GitHub gist 需要它们 执行此操作的最佳做 法是什么 使用iframe 创造script动态标记 或者是其他东西 一种方法是创建一个iframe with script里面并在你希望你
  • 这是复制类的好方法吗? [关闭]

    Closed 这个问题是基于意见的 help closed questions 目前不接受答案 我是一个十足的菜鸟 所以如果我不适合问这个问题 请告诉我 如果需要的话请给我引导 无论如何 我一直在学习值类型和引用类型 并且想知道定义一个像这
  • 文件中缺少所需的架构 i386

    添加 MapKit 和 CoreLocation 框架后 我在构建应用程序时遇到问题 它们都是 4 3 框架 并且该应用程序过去可以与 UIKit CoreGraphics 和 Foundation 一起正常工作 只是这两个框架给我带来了问
  • InstallShield XML 文件更改 - 安装时更改节点属性

    我正在使用 InstallShield 2012 构建 Web 服务安装 并且需要根据用户输入修改应用程序的 Web config 文件 我在 DestinationFolder 对话框之后引入了 PromptServerAndDataba
  • Javascript:更改浏览器后退按钮的功能

    有没有办法让用户的浏览器上的后退按钮调用 JavaScript 函数而不是返回页面 您无法覆盖这样的行为 如果用户通过链接访问您的页面 则单击 后退 将使他们再次离开该页面 但是 您可以使页面上的 JavaScript 操作将条目添加到历史
  • javax.el.PropertyNotFoundException:在 java.lang.String 类型上找不到属性“tname”

    我之前使用的是 scriptlet 但现在我改用了 mvc 我无法检索 JSP 页面上的值并收到错误 javax el PropertyNotFoundException Property tname not found on type j
  • 如何在 Swift 中将 Int 转换为字符

    我在这里挣扎了十多分钟 失败了 我屈服了 我需要在 Swift 中将 Int 转换为 Character 但无法解决它 Question 你如何转换 cast an Int integer to a Character char 在斯威夫特
  • Spring的@PreDestroy导致随机记录而不记录

    我正在使用 Spring 并且在终止时我让 PreDestroy 清理 bean 我不明白为什么日志记录有时会成功 而有时会失败 Using Log4j2 Logger log LogManager getLogger MyClass cl
  • VS Code Pylint 在缺失的函数/类文档字符串上用蓝色下划线突出显示整个函数

    这种情况突然开始发生 当出现缺少函数文档字符串警告时 python pylint 会用蓝色波浪线突出显示整个函数 我怎样才能让它只突出显示函数定义或在定义行上制作一个小指示器 在开发时突出显示整个文件是非常烦人的 这是缺少类文档字符串的示例
  • 使用 Kotlin 协程替换 LocalBroadcastManager 以进行 Firebase 消息传递

    使用时Firebase 云消息传递 https firebase google com docs cloud messaging android client在 Android 上 通常需要通知当前Activity传入的推送通知 推荐的方法
  • Capybara 2.0 和 rspec-rails -- 助手在规范/功能中不起作用

    我正在尝试使用辅助模块中的方法 但 rspec 似乎无法识别辅助程序以进行测试spec features 请注意 唯一的更改是spec helper rb正在添加require capybara rspec 我尝试移动helper rb t
  • 无法实施第三方 Google 日历会议插件

    我正在研究 Google 日历会议插件的实施并发现了一些问题 我按照文档执行示例代码 但它没有按预期工作 从我的角度来看 我的清单文件是完整的 但是当我尝试从 从清单部署 链接发布日历会议插件时 它会打开我的谷歌日历 但它不会显示我的会议
  • 从内存中发送图像

    我正在尝试为 Discord 机器人实现一个系统 该系统可以动态修改图像并将其发送给机器人用户 为此 我决定使用 Pillow PIL 库 因为它对于我的目的来说似乎简单明了 这是我的工作代码的示例 它加载一个示例图像 作为测试修改 在其上
  • ASIHTTPRequest:检测到不正确的 NSStringEncoding 值 0x0000

    检测到不正确的 NSStringEncoding 值 0x0000 假设 NSStringEncodingASCII 将停止此兼容性映射行为 不久的将来 当我使用 ASIHTTPRequest 时 我不断收到此错误 50 的时间 这是怎么回
  • Redis是如何实现高吞吐量和高性能的?

    我知道这是一个非常普遍的问题 但是 我想了解允许 Redis 或 MemCached Cassandra 等缓存 以惊人的性能极限工作的主要架构决策是什么 如何维持连接 连接是 TCP 还是 HTTP 我知道它完全是用C写的 内存是如何管理
  • ImageMagick 调整大小 - 设置横向和纵向图像的宽度

    我正在尝试将图像调整为给定宽度 按比例调整高度 无论图像是横向还是纵向 我有两张图像我测试了 ImageMagickconvert resize根据我所读到的命令 我希望以下内容适用于任何类型的图像 convert source jpg r
  • 如何使用 iTextSharp 设置 PDF 段落或字体行高?

    如何使用 iTextSharp 更改 PDF 字体或段落的行高 排版中的行距称为行距 如果可以使用行间距 则可以使用 Paragraph Leading 或 Paragraph LeadingMultiplier 看http itextsh
  • iOS-Swift UIApplication.shared.isIdleTimerDisabled = true 在 AppStore 审核后不起作用

    努力实现停止屏幕在某些情况下进入睡眠状态View Controller 我做了什么我已在运行 iOS 12 1 12 的物理 iPhone 6 上使用以下代码测试了我的应用程序 我设置了手机Dislpay Brigthness gt Aut
  • speex 烦人的蜱虫[关闭]

    这个问题不太可能对任何未来的访客有帮助 它只与一个较小的地理区域 一个特定的时间点或一个非常狭窄的情况相关 通常不适用于全世界的互联网受众 为了帮助使这个问题更广泛地适用 访问帮助中心 help reopen questions 我正在制作
  • DynamoDB 中条件写入的日期时间比较

    我目前正在使用 DynamoDB 如果该记录的日期早于新记录日期字段 我想使用条件写入来更新该记录 有没有办法比较条件写入的 DateTime 类型 或者目前仅适用于整数 字符串和流 Thanks 既然你提到你正在使用ISO 8601 ht