Delete by Hashkey Using DynamoDB Mapper (Guide w/ Code Examples)

Provided by Rafal Wilinski
Last updated: October 23rd, 2026
Deleting a partition-key value is not a single API operation when the table has a sort key. Query the item collection, then delete each complete key.
DynamoDBMapper belongs to AWS SDK for Java 1.x and cannot be constructed with a 2.x DynamoDbClient. The example below shows the SDK 2.x low-level equivalent. For mapped domain objects, use the DynamoDB Enhanced Client.
This example uses Java 17+ and the software.amazon.awssdk:dynamodb SDK 2.x dependency. Configure an AWS Region and credentials through your usual AWS profile or runtime role. The Orders table has String keys pk and sk; adapt the table and keys to your schema.
import java.util.*; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.*; public class Example { static AttributeValue s(String value) { return AttributeValue.builder().s(value).build(); } static Map<String, AttributeValue> key(String order) { return Map.of("pk", s("CUSTOMER#123"), "sk", s(order)); } public static void main(String[] args) throws InterruptedException { try (DynamoDbClient ddb = DynamoDbClient.create()) { QueryRequest request = QueryRequest.builder().tableName("Orders") .keyConditionExpression("#pk = :pk") .expressionAttributeNames(Map.of("#pk", "pk")) .expressionAttributeValues(Map.of(":pk", s("CUSTOMER#123"))).build(); for (QueryResponse page : ddb.queryPaginator(request)) { for (Map<String, AttributeValue> item : page.items()) { ddb.deleteItem(DeleteItemRequest.builder().tableName("Orders") .key(Map.of("pk", item.get("pk"), "sk", item.get("sk"))).build()); } } } } }
Stop concurrent writes for a maintenance purge. The query and deletes do not form one atomic operation, and new items may appear during the job.
Reference: AWS DeleteItem API. For related access patterns, see DynamoDB query examples.
Similar Code Examples
- Query Global Secondary Index in DynamoDB Using Java
- Remove Attribute in DynamoDB Using Java
- Remove with DynamoDB Mapper
- Query Index in DynamoDB Using Java
- Get Multiple Items in DynamoDB Using Java
- Query Date Range in DynamoDB Using Java
- Batch Get in DynamoDB Using Java
- Batch Delete Using DynamoDB Mapper
- Get Item Request in DynamoDB Using Java
- Query Hash Key Only in DynamoDB Using Java
- Batch Write Item in DynamoDB Using Java
- Batch Write Using DynamoDB Mapper
- Batch Query in DynamoDB Using Java
- Delete All Items in DynamoDB Using Java
- Conditional Update in DynamoDB Using Java
Dynobase is a Professional GUI Client for DynamoDB
Start your 7-day free trial today