Delete records
For the complete documentation index see: llms.txt
All documentation pages available in markdown.
Applies to
- Aerospike Developer SDK (Java 21+ and Python 3.11+)
- Aerospike Database 8.2.0 or later, unless a section states otherwise
Learn how to delete records from Aerospike using the Developer SDK. This guide covers simple deletion, conditional deletes, and handling deletion of non-existent records.
Except where noted, snippets on this page use the imports below. A snippet lists additional import lines only when it needs a type not shown here. When this page includes a Complete example section, that block is fully self-contained with every import required to run it.
import com.aerospike.client.sdk.AerospikeException;import com.aerospike.client.sdk.DataSet;import com.aerospike.client.sdk.Record;import com.aerospike.client.sdk.RecordResult;import com.aerospike.client.sdk.RecordStream;
import java.time.Duration;import java.util.ArrayList;import java.util.List;import time
from aerospike_sdk import DataSet, GenerationErrorDelete a record
Use delete() to remove a record by its key:
DataSet users = DataSet.of("test", "users");
session.delete(users.id("user-1")) .execute();📖 API reference:
DataSet.of(...)|DataSet.id(...)|Session.delete(Key)|ChainableQueryBuilder.execute()
users = DataSet.of("test", "users")await session.delete(users.id("user-1")).execute()📖 API reference:
DataSet.of()|DataSet.id()|Session.delete()|WriteSegmentBuilder.execute()
Check if delete succeeded
Use the delete result row to determine whether a record was actually deleted:
DataSet users = DataSet.of("test", "users");
RecordStream deleteStream = session.delete(users.id("user-1")).execute();boolean deleted = deleteStream.getFirst().map(RecordResult::asBoolean).orElse(false);
if (deleted) { System.out.println("Record deleted successfully");} else { System.out.println("Record didn't exist");}📖 API reference:
DataSet.id(...)|Session.delete(Key)|ChainableQueryBuilder.execute()|RecordStream.getFirst()
users = DataSet.of("test", "users")deleted = (await session.delete(users.id("user-1")).first()).as_bool()
if deleted: print("Record deleted successfully")else: print("Record didn't exist")📖 API reference:
DataSet.of()|DataSet.id()|Session.delete()|RecordResult.as_bool()|RecordStream.first()|RecordStream.close()|WriteSegmentBuilder.execute()
Conditional delete (generation check)
Delete only if the record hasn’t been modified since you last read it:
DataSet users = DataSet.of("test", "users");
// Read the record firstRecordStream readStream = session.query(users.id("user-1")).execute();Record user = readStream.getFirstRecord();
// Delete only if generation matchestry { session.delete(users.id("user-1")) .ensureGenerationIs(user.generation) .execute(); System.out.println("Deleted successfully");} catch (AerospikeException.GenerationException e) { System.out.println("Record was modified, delete aborted");}📖 API reference:
DataSet.id(...)|Session.delete(Key)|Session.query(Key)|ChainableQueryBuilder.execute()|RecordStream.getFirstRecord()|AerospikeException
users = DataSet.of("test", "users")# Read the record firstrow = await session.query(users.id("user-1")).first_or_raise()user = row.record_or_raise()
# Delete only if generation matchestry: await ( session.delete(users.id("user-1")) .ensure_generation_is(user.generation) .execute() ) print("Deleted successfully")except GenerationError: print("Record was modified, delete aborted")📖 API reference:
DataSet.of()|DataSet.id()|Session.query()|Session.delete()|WriteSegmentBuilder.ensure_generation_is()|RecordResult.record_or_raise()|RecordStream.first_or_raise()|RecordStream.close()|QueryBuilder.execute()|WriteSegmentBuilder.execute()
Delete only if exists
By default, deleting a non-existent record is a no-op. In Java, use exists() first if you need a hard failure when the record is missing. In Python, check existence first and then delete. Note in both cases it is possible for the record to have been deleted by another thread between the return of the exists() check and when the result is actioned. To avoid this race condition, either use a transaction or check whether the delete result’s code (getResultCode() in Java, result_code in Python) is KEY_NOT_FOUND_ERROR.
DataSet users = DataSet.of("test", "users");
// There is no deleteOnly() in the Java SDK; check existence first if you must fail when absent.boolean existed = session.exists(users.id("user-1")).execute().getFirstBoolean().orElse(false);if (!existed) { System.out.println("Record not found");} else { session.delete(users.id("user-1")).execute().close(); System.out.println("Record deleted");}📖 API reference:
DataSet.id(...)|Session.delete(Key)|Session.exists(Key)|ChainableQueryBuilder.execute()|ChainableNoBinsBuilder.execute()|RecordStream.close()
users = DataSet.of("test", "users")
existed = (await session.exists(users.id("user-1")).first()).as_bool()
if not existed: print("Record not found")else: await session.delete(users.id("user-1")).execute() print("Record deleted")📖 API reference:
DataSet.of()|DataSet.id()|Session.delete()|Session.exists()|RecordResult.as_bool()|RecordStream.first()|RecordStream.close()|WriteSegmentBuilder.execute()
Delete with durability options
For critical deletes, ensure durability. These can either be done on a per-call basis, or set on the session level with a Behavior.
DataSet users = DataSet.of("test", "users");
// Request a durable delete for this callsession.delete(users.id("important-record")) .withDurableDelete() .execute();📖 API reference:
DataSet.id(...)|Session.delete(Key)|ChainableQueryBuilder.execute()
users = DataSet.of("test", "users")
# Request a durable delete for this callawait session.delete(users.id("important-record")).with_durable_delete().execute()📖 API reference:
DataSet.id()|Session.delete()|WriteSegmentBuilder.execute()
📖 Learn more: Behaviors explains durability options.
Batch delete
For deleting multiple records efficiently, see Batch Operations.
DataSet users = DataSet.of("test", "users");
// Quick preview - see Batch Operations for full detailsRecordStream deleteStream = session.delete(users.ids("user-1", "user-2", "user-3")).execute();📖 API reference:
DataSet.ids(...)|Session.delete(List)|Session.delete(Key)|ChainableQueryBuilder.execute()
users = DataSet.of("test", "users")
# Quick preview - see Batch Operations for full detailsawait session.delete(users.ids("user-1", "user-2", "user-3")).execute()📖 API reference:
DataSet.ids()|Session.delete()
Soft delete pattern
Instead of permanently deleting, mark records as deleted:
DataSet users = DataSet.of("test", "users");
// Soft delete: mark as deleted instead of removingsession.update(users.id("user-1")) .bin("deleted").setTo(true) .bin("deleted_at_ms").setTo(System.currentTimeMillis()) .execute();
// When querying, filter out deleted recordsRecordStream stream = session.query(users) .where("$.deleted == false") .execute();List<Record> activeUsers = new ArrayList<>();stream.forEach(result -> { if (result.isOk()) { activeUsers.add(result.recordOrThrow()); }});// forEach is a terminal operation and closes the stream.📖 API reference:
DataSet.id(...)|Session.update(Key)|Session.query(DataSet)|ChainableOperationBuilder.bin(...)|ChainableQueryBuilder.where(...)|ChainableQueryBuilder.execute()|RecordStream.forEach(...)|RecordResult.isOk()|RecordResult.recordOrThrow()
users = DataSet.of("test", "users")# Soft delete: mark as deleted instead of removingawait ( session.update(users.id("user-1")) .bin("deleted").set_to(True) .bin("deleted_at_ms").set_to(int(time.time() * 1000)) .execute())
# When querying, filter out deleted recordsstream = await session.query(users).where("$.deleted == false").execute()active_users = []async for row in stream: active_users.append(row.record_or_raise())stream.close()📖 API reference:
DataSet.of()|DataSet.id()|Session.query()|Session.update()|QueryBuilder.where()|QueryBuilder.bin()|WriteSegmentBuilder.set_to()|WriteSegmentBuilder.bin()|RecordResult.record_or_raise()|RecordStream.close()|QueryBuilder.execute()|WriteSegmentBuilder.execute()
Delete with TTL (auto-expire)
Instead of explicit deletion, let records expire automatically. Note: do not decrease the expiration time on a record.
DataSet users = DataSet.of("test", "users");
// Set TTL to expire in 1 minute (deferred delete)session.touch(users.id("user-1")) .expireRecordAfter(Duration.ofMinutes(1)) .execute();📖 API reference:
DataSet.id(...)|Session.touch(Key)|ChainableQueryBuilder.execute()
users = DataSet.of("test", "users")
# Set TTL to expire in 1 minute (deferred delete)await ( session.touch(users.id("user-1")) .expire_record_after_seconds(60) .execute())📖 API reference:
DataSet.id()|Session.touch()|WriteSegmentBuilder.expire_record_after_seconds()|WriteSegmentBuilder.execute()
Complete example
This example is self-contained—it lists every import needed to run standalone.
import com.aerospike.client.sdk.Cluster;import com.aerospike.client.sdk.ClusterDefinition;import com.aerospike.client.sdk.DataSet;import com.aerospike.client.sdk.Record;import com.aerospike.client.sdk.RecordResult;import com.aerospike.client.sdk.RecordStream;import com.aerospike.client.sdk.Session;import com.aerospike.client.sdk.policy.Behavior;
public class DeleteRecordsExample { public static void main(String[] args) { try (Cluster cluster = new ClusterDefinition("localhost", 3000).connect()) { Session session = cluster.createSession(Behavior.DEFAULT); DataSet users = DataSet.of("test", "users"); String deleteKey = "delete-example-user"; String conditionalKey = "delete-example-conditional";
// Cleanup so the example is repeatable. session.delete(users.id(deleteKey)).execute().close(); session.delete(users.id(conditionalKey)).execute().close();
// Create a test record session.insert(users) .bins("name") .id(deleteKey).values("Test User") .execute();
// Simple delete RecordStream deletedStream = session.delete(users.id(deleteKey)).execute(); boolean deleted = deletedStream.getFirst().map(RecordResult::asBoolean).orElse(false); System.out.println("Deleted: " + deleted);
// Try to delete again (returns false) RecordStream secondDeletedStream = session.delete(users.id(deleteKey)).execute(); deleted = secondDeletedStream.getFirst(false).map(RecordResult::asBoolean).orElse(false); secondDeletedStream.close(); System.out.println("Second delete: " + deleted);
// Conditional delete example session.insert(users) .bins("name") .id(conditionalKey).values("Conditional User") .execute();
RecordStream rs = session.query(users.id(conditionalKey)).execute(); Record record = rs.getFirstRecord();
session.delete(users.id(conditionalKey)) .ensureGenerationIs(record.generation) .execute(); System.out.println("Conditional delete succeeded"); } }}📖 API reference:
ClusterDefinition(String,int)|ClusterDefinition.connect()|Cluster.createSession(Behavior)|Cluster.close()|DataSet.of(...)|Session.insert(DataSet)|Session.delete(Key)|Session.query(Key)|OperationObjectBuilder.bins(...)|IdValuesBuilder.id(...)|IdValuesRowBuilder.values(...)|ChainableQueryBuilder.execute()|ChainableNoBinsBuilder.execute()|RecordStream.getFirstRecord()|RecordStream.getFirst()|RecordStream.close()
import asynciofrom aerospike_sdk import Behavior, DataSet, ClusterDefinition
async def main(): async with ClusterDefinition("localhost", 3000).connect() as cluster: session = cluster.create_session(Behavior.DEFAULT) users = DataSet.of("test", "users") delete_key = users.id("delete-example-user") conditional_key = users.id("delete-example-conditional")
# Cleanup so the example is repeatable. await session.delete(delete_key).execute() await session.delete(conditional_key).execute()
# Create a test record await session.insert(delete_key).put( {"name": "Test User"} ).execute()
# Simple delete deleted = (await session.delete(delete_key).first()).as_bool() print(f"Deleted: {deleted}")
# Try to delete again (returns False) deleted = (await session.delete(delete_key).first()).as_bool() print(f"Second delete: {deleted}")
# Conditional delete example await session.insert(conditional_key).put( {"name": "Conditional User"} ).execute()
row = await session.query(conditional_key).first_or_raise() record = row.record_or_raise()
await ( session.delete(conditional_key) .ensure_generation_is(record.generation) .execute() ) print("Conditional delete succeeded")
if __name__ == "__main__": asyncio.run(main())📖 API reference:
ClusterDefinition|Cluster.create_session()|DataSet.of()|DataSet.id()|Behavior.DEFAULT|Session.query()|Session.insert()|Session.delete()|WriteSegmentBuilder.put()|WriteSegmentBuilder.ensure_generation_is()|RecordResult.record_or_raise()|RecordResult.as_bool()|RecordStream.first()|RecordStream.first_or_raise()|RecordStream.close()|QueryBuilder.execute()|WriteSegmentBuilder.execute()
API reference summary
| Method | Description | Link |
|---|---|---|
delete() | Delete a record by key | Java · Python |
.ensureGenerationIs(gen) / .ensure_generation_is(gen) | Conditional delete | — |
(No deleteOnly / delete_only in either SDK) | Use exists() then delete(), or inspect the delete result | — |
Next steps
Batch Operations
Delete multiple records efficiently.
Query Records
Find records to delete with DSL queries.
Error Handling
Handle deletion errors gracefully.