如何在 DynamoDB 中基于 HashKey 和 Range Key 进行查询?

2022-09-04 00:44:13

我是新手。我只想知道如何在 DynamoDB 中使用 and 查询表。DynamoDbhashKeyrangeKey

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

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

现在,如果我想在此基础上查询此表,我们将其设置为:hashKeyIdquery

假设我的查询是获取所有具有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


答案 1

前段时间,我写了一篇关于 DynamoDB 使用 AWS Java 开发工具包进行查询和索引的文章: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 对象持久性模型部分。


答案 2

你可以使用 dynamoDbMapper.load() 如下所示:

TestTable testTable = new TestTable();
testTable.setId("123");
testTable.setDate("1234");
TestTable result = dynamoDBMapper.load(testTable);

推荐