Skip to content

Create records

Learn how to create records in Aerospike using the Developer SDK. This guide covers inserting new records, upserting, setting TTL, and working with complex data types.

Insert a single record

Use insert() to create a new record. This fails if the record already exists.

DataSet users = DataSet.of("test", "users");
session.insert(users)
.bins("name", "email", "age")
.id("user-1").values("Alice Smith", "alice@example.com", 28)
.execute();

Upsert (insert or update)

Use upsert() when you want to create a record if it doesn’t exist, or update it if it does.

// Creates or updates the record
session.upsert(users)
.bins("name", "email", "age")
.id("user-1").values("Alice Smith", "alice.smith@example.com", 29)
.execute();

Insert vs upsert vs other operations

MethodRecord ExistsRecord Doesn’t ExistMerges with Existing Data
insert()❌ Fails with error✅ Creates recordNot Applicable
upsert()✅ Updates record✅ Creates record✅ Yes
update()✅ Updates record❌ Fails with error✅ Yes
replace()✅ Updates record✅ Creates record❌ No
replaceIfExists() / replace_if_exists()✅ Updates record❌ Fails with error❌ No

Rule of thumb: Use insert() when you expect the record to be new and want to catch duplicates. Use upsert() when you don’t care whether it exists.

Set time-to-live (TTL)

Records can automatically expire after a specified duration, or at a specified time:

import java.time.Duration;
import com.aerospike.client.sdk.AerospikeException;
// Record expires in 1 hour
try {
session.insert(users)
.bins("token", "user_id")
.id("session-token").values("abc123", "user-1")
.expireRecordAfter(Duration.ofHours(1))
.execute();
} catch (AerospikeException e) {
// Can fail with "Operation not allowed at this time" when TTL prerequisites are not met.
System.err.println("TTL write failed: " + e.getMessage());
}
// Record expires on 1st January, 2030 (UTC)
session.insert(users)
.bins("name")
.id("user-1").values("Alice")
.expireRecordAt(LocalDateTime.of(2030,1,1,0,0,0))
.execute();
// Record never expires (override namespace default)
session.insert(users.id("permanent-user"))
.bin("name").setTo("System Admin")
.neverExpire()
.execute();

Store the user key

By default, Aerospike only stores a digest (hash) of the key. To retrieve the original key later, enable send-key on the behavior used by the session — sendKey(true) in Java, send_key=True in Python:

import com.aerospike.client.sdk.RecordResult;
import com.aerospike.client.sdk.RecordStream;
Behavior sendKeyBehavior = Behavior.DEFAULT.deriveWithChanges("sendKey", builder ->
builder.on(Selectors.all(), op -> op.sendKey(true)));
Session session = cluster.createSession(sendKeyBehavior);
session.update(users)
.bins("name")
.id("user-12345").values("Alice")
.execute();
// Later, when reading:
session.query(users.id("user-12345"))
.execute()
.getFirst()
.ifPresent(result ->
System.out.printf("key: %s\n", result.key().userKey). // user-12345
);
}

Create with complex data types

Aerospike supports lists and maps as bin values:

import java.util.List;
import java.util.Map;
// List values
session.insert(users)
.bins("name", "tags", "scores")
.id("user-1").values(
"Alice",
List.of("premium", "verified", "active"),
List.of(95, 87, 92, 88)
)
.execute();
// Map values
session.insert(users.id("user-1")
.bin("name").setTo("Alice")
.bin("preferences").setTo(
Map.of("theme", "dark", "language", "en", "notifications", true));
.execute();
// Nested structures
session.insert(users)
.bins("name", "address")
.id("user-1").values(
"Alice",
Map.of(
"street", "123 Main St",
"city", "San Francisco",
"coordinates", List.of(37.7749, -122.4194)
)
)
.execute();

📖 Learn more: Data Model explains Aerospike’s data types in detail.

Create only if not exists

Use insert() with error handling to implement “create only if not exists” logic:

import com.aerospike.client.sdk.AerospikeException;
try {
session.insert(users)
.bins("name")
.id("user-1").values("Alice")
.execute();
System.out.println("User created successfully");
} catch (AerospikeException.RecordExistsException e) {
System.out.println("User already exists, skipping creation");
}

📖 Learn more: Error Handling covers all exception types.

Batch create

For creating multiple records efficiently, see Batch Operations.

// Quick preview - see Batch Operations for full details
session.insert(users)
.bins("name")
.id("user-1").values("Alice")
.id("user-2").values("Bob")
.id("user-3").values("Carol")
.execute();

Complete example

import com.aerospike.client.sdk.Cluster;
import com.aerospike.client.sdk.ClusterDefinition;
import com.aerospike.client.sdk.DataSet;
import com.aerospike.client.sdk.Session;
import com.aerospike.client.sdk.policy.Behavior;
import java.util.List;
import java.util.Map;
public class CreateRecordsExample {
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 key = "create-example-user";
// Cleanup so the example is repeatable.
session.delete(users.id(key)).execute();
// Simple insert
session.insert(users)
.bins("name", "email", "age")
.id(key).values("Alice Smith", "alice@example.com", 28)
.execute();
// Upsert with complex data
session.upsert(users)
.bins("name", "tags", "preferences")
.id(key).values(
"Alice Smith",
List.of("premium", "verified"),
Map.of("theme", "dark")
)
.execute();
System.out.println("Records created successfully!");
}
}
}

API reference summary

MethodDescriptionLink
insert()Create a new record (fails if exists)Java · Python
upsert()Create or update a recordJava · Python
.bins(...) / .put({...})Set bin values
.expireRecordAfter(duration) / .expire_record_after_seconds(seconds)Set time-to-live
.expireRecordsAt(localDateTime) (Java only)Expire records at a wall-clock time
.neverExpire() / .never_expire()Pin record TTL to never expire

Next steps

Feedback

Was this page helpful?

What type of feedback are you giving?

What would you like us to know?

+Capture screenshot

Can we reach out to you?