0

我有一个表Book,其中bookIdlastBorrowed分别作为哈希键和范围键。假设每次借书时,都会创建一个新行。

(是的,这还不够,我可以添加一个列来跟踪计数和更新lastBorrowed日期。但假设我坚持这个设计,我无能为力。)

给定一组bookIds(或hashKeys),我希望能够查询每本书最后一次被借阅的时间。

我试图使用QueryRequest,但不断得到com.amazonaws.AmazonServiceException: Attempted conditional constraint is not an indexable operation

final Map<String, Condition> keyConditions =
                Collections.singletonMap(hashKeyFieldName, new Condition()
                 .withComparisonOperator(ComparisonOperator.IN)
                 .withAttributeValueList(hashKeys.stream().map(hashKey -> new AttributeValue(hashKey)).collect(Collectors.toList())));

我也尝试过使用BatchGetItemRequest,但也没有用:

final KeysAndAttributes keysAndAttributes = new KeysAndAttributes() .withConsistentRead(areReadsConsistent);
hashKeys.forEach(hashKey -> { keysAndAttributes.addExpressionAttributeNamesEntry(hashKeyFieldName, hashKey); });

final Map<String, KeysAndAttributes> requestedItemsByTableName = newHashMap();
requestedItemsByTableName.put(tableName, keysAndAttributes);

final BatchGetItemRequest request = new BatchGetItemRequest().withRequestItems(requestedItemsByTableName);

任何建议将不胜感激!或者,如果有人可以告诉我这目前根本不支持,那么我想我会继续前进!

4

1 回答 1

0

你可以做到这一点,事实上它很容易。您所要做的就是为您的 bookId 执行一个查询,然后获取第一个结果。

顺便说一句,您的表设计听起来非常好,唯一的问题是属性可能应该被称为借用而不是最后借用。

单个 bookId 可以有多个结果,但由于 lastBorrowed 是您的范围键,结果将按该属性排序。

您似乎正在使用Legacy Functions,您在编辑旧代码吗?

如果没有,请执行您的查询,如下所示:

//Setting up your DynamoDB connection
AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard()
.withRegion(Regions.US_WEST_2).build();
DynamoDB dynamoDB = new DynamoDB(client);
Table table = dynamoDB.getTable("YOURTABLE");

//Define the Query
QuerySpec spec = new QuerySpec()
    .withKeyConditionExpression("bookId = :book_id)
    .withValueMap(new ValueMap()
        .withString(":book_id", "12345")
    .withScanIndexForward(true);

//Execute the query
ItemCollection<QueryOutcome> items = table.query(spec);

//Print out your results - take the first item
Iterator<Item> iterator = items.iterator();
while (iterator.hasNext()) {
    System.out.println(iterator.next().toJSONPretty());
}
于 2018-02-04T12:28:55.507 回答