java - 如何在DynamoDB中基于HashKey和range Key做Query?

标签 java amazon-dynamodb

我是新来的 DynamoDb东西。我只想知道我们如何使用 hashKey 查询 DynamoDB 中的表和 rangeKey .

假设我的表是 TestTable它的架构是这样的:

1.Id (HK of type String)
2 Date (RK of type String )
3 Name (attribute of type String)

现在如果我想根据 hashKey 在这个表上查询这是 Id在这里,我们做了一个 query作为 :

假设我的查询是获取所有具有 Id ="123". 的项目
TestTable testTable = new TestTable();
testTable.setId("123");

DynamoDBQueryExpression<TestTable> queryExpression = new DynamoDBQueryExpression<TestTable>()
                                                                .withHashKeyValues(TestTable)
                                                                .withConsistentRead(false);

现在我想获得所有具有 Id ="123" and Date ="1234" 的项目.

我如何在 DynamoDB 中查询这个东西

我正在使用 java作为我的编程语言。

最佳答案

前段时间我写了一篇关于使用 AWS Java SDK 进行 DynamoDB 查询和索引的文章: http://labs.journwe.com/2013/12/15/dynamodb-secondary-indexes/

在您的情况下,它应该像这样工作(请参阅 http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/JavaQueryScanORMModelExample.html ):

AmazonDynamoDBClient client = new AmazonDynamoDBClient(new ProfileCredentialsProvider());
DynamoDBMapper mapper = new DynamoDBMapper(client);

String hashKey = "123";
long twoWeeksAgoMilli = (new Date()).getTime() - (15L*24L*60L*60L*1000L);
Date twoWeeksAgo = new Date();
twoWeeksAgo.setTime(twoWeeksAgoMilli);
SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
dateFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
String twoWeeksAgoStr = dateFormatter.format(twoWeeksAgo);            
Condition rangeKeyCondition = new Condition()
        .withComparisonOperator(ComparisonOperator.GT.toString())
        .withAttributeValueList(new AttributeValue().withS(twoWeeksAgoStr.toString()));

Reply replyKey = new Reply();
replyKey.setId(hashKey);

DynamoDBQueryExpression<Reply> queryExpression = new DynamoDBQueryExpression<Reply>()
        .withHashKeyValues(replyKey)
        .withRangeKeyCondition("ReplyDateTime", rangeKeyCondition);

List<Reply> latestReplies = mapper.query(Reply.class, queryExpression);

查看 DynamoDB 文档的 Java 对象持久性模型部分了解更多信息。

关于java - 如何在DynamoDB中基于HashKey和range Key做Query?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30840093/

相关文章:

java - 如何使用 hibernate validator 检查枚举中的值是否可用

amazon-web-services - DynamoDB PutItem 上的条件表达式

mysql - 检查给定句子(查询)是否包含任何预定义关键字的最佳方法

amazon-web-services - 如何在不构建依赖项的情况下引用堆栈输出值?

python - 使用 boto3 dynamodb 客户端时出现 FilterExpression 语法错误

java - 使用barcode4j 添加补充到EAN13 条形码

java - 通过 osmdroid 上的网络提供商获取当前位置

java - .gradlew在WSL上找不到证书Debian Stretch

java - Scala 读取并解析 JSON

amazon-dynamodb - 如何解决这个异常 : "Cannot specify the AttributesToGet when choosing to get ALL_ATTRIBUTES"?