DeleteItem API 引发错误 - 提供的关键元素与架构 (DynamoDB) 不匹配

问题描述 投票:0回答:1

我正在使用 java v2 sdk 并尝试使用下面的代码从表中删除项目

public static DeleteItemResponse deleteDynamoDBItem(String key, String keyVal) {

    Map<String, AttributeValue> keyToGet =
            new HashMap<>();

    keyToGet.put(key, AttributeValue.builder()
            .s(keyVal)
            .build());

    DeleteItemRequest deleteReq = DeleteItemRequest.builder()
            .tableName(TABLE_NAME)
            .key(keyToGet)
            .build();

    try {
        return DYNAMO_DB.deleteItem(deleteReq);
    } catch (DynamoDbException e) {
        System.err.println(e.getMessage());
        System.exit(1);
    }
    return null;
}

日志中抛出错误

“提供的关键元素与架构不匹配(服务:DynamoDb,状态代码:400,请求 ID:VCTLMOSSUBMSHMCNOMN589ETPJVV4KQNSO5AEMVJF66Q9ASUAAJG)”

DeleteItemResponse response = DataService.deleteDynamoDBItem("userid", "abc");

以下是表结构

enter image description here

enter image description here

我指的是下面的网址为例

https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/DeleteItem.java

java amazon-web-services aws-lambda amazon-dynamodb
1个回答
0
投票

在 DynamoDB 中,如果表同时具有分区键和排序键,则任何操作(如 DeleteItem)都必须为两个键提供值以唯一标识该项目。 所以你的代码应该是这样的:

public static DeleteItemResponse deleteDynamoDBItem(String partitionKey, String partitionKeyValue, String sortKey, int sortKeyValue) {

    Map<String, AttributeValue> keyToGet = new HashMap<>();

    keyToGet.put(partitionKey, AttributeValue.builder()
            .s(partitionKeyValue) // Partition key is a String
            .build());
    keyToGet.put(sortKey, AttributeValue.builder()
            .n(String.valueOf(sortKeyValue)) // Sort key is a Number, so convert int to String
            .build());

    DeleteItemRequest deleteReq = DeleteItemRequest.builder()
            .tableName(TABLE_NAME)
            .key(keyToGet)
            .build();

    try {
        return DYNAMO_DB.deleteItem(deleteReq);
    } catch (DynamoDbException e) {
        System.err.println(e.getMessage());
        System.exit(1);
    }
    return null;
}

然后您可以轻松拨打:

DeleteItemResponse response = DataService.deleteDynamoDBItem("userid", "abc", "age", 89);
© www.soinside.com 2019 - 2024. All rights reserved.