---
title: "Create records"
description: "Learn to insert and upsert records in Aerospike using Java and Python SDKs, including TTL and collection data types (CDTs)."
---

# Create records

> For the complete documentation index see: [llms.txt](https://aerospike.com/docs/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

::: code examples
Examples assume a connected `session` from [Connect to Aerospike](https://aerospike.com/docs/develop/client/sdk/connect). Each usage guide lists shared imports in a tabbed block near the top of the page; snippet blocks add imports only for types not already shown. The first code block in each section includes dataset setup; later blocks in that section reuse those values. When a page includes a **Complete example** section, that block is fully self-contained.
:::

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

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.

-   [Java](#tab-panel-5394)
-   [Python](#tab-panel-5395)

```java
import com.aerospike.client.sdk.AerospikeException;

import com.aerospike.client.sdk.DataSet;

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.Selectors;

import com.aerospike.client.sdk.policy.Behavior;

import java.time.Duration;

import java.time.LocalDateTime;

import java.util.List;

import java.util.Map;
```

```python
from datetime import datetime, timedelta

from aerospike_sdk import Behavior, DataSet

from aerospike_sdk.exceptions import AerospikeError, ResultCode

from aerospike_sdk.policy import Settings
```

## Insert a single record

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

-   [Java](#tab-panel-5396)
-   [Python](#tab-panel-5397)

Write calls take one of two forms with separate methods:

-   Pass a dataset, as in `session.insert(users)`, to list bin names once with `.bins(...)` and then supply each record with `.id(...).values(...)`.
-   Pass a key, as in `session.insert(users.id("user-1"))`, to set each bin with `.bin(name).setTo(value)`. This form has no `.bins(...)` method. Use it for map values.

```java
DataSet users = DataSet.of("test", "users");

session.insert(users)

    .bins("name", "email", "age")

    .id("user-1").values("Alice Smith", "alice@example.com", 28)

    .execute();
```

> 📖 **API reference**: [`DataSet.of(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/DataSet.html#of%28java.lang.String%2Cjava.lang.String%29) | [`Session.insert(DataSet)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/Session.html#insert%28com.aerospike.client.sdk.DataSet%29) | [`OperationObjectBuilder.bins(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/OperationObjectBuilder.html#bins%28java.lang.String%2Cjava.lang.String...%29) | [`IdValuesBuilder.id(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/IdValuesBuilder.html#id%28java.lang.String%29) | [`IdValuesRowBuilder.values(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/IdValuesRowBuilder.html#values%28java.lang.Object...%29) | [`ChainableQueryBuilder.execute()`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/ChainableQueryBuilder.html#execute%28%29)

```python
users = DataSet.of("test", "users")

await session.insert(users.id("user-1")).put(

    {"name": "Alice Smith", "email": "alice@example.com", "age": 28}

).execute()
```

> 📖 **API reference**: [`DataSet.of()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/dataset.html#aerospike%5Fsdk.dataset.DataSet.of) | [`DataSet.id()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/dataset.html#aerospike%5Fsdk.dataset.DataSet.id) | [`Session.insert()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/session.html#aerospike%5Fsdk.aio.session.Session.insert) | [`WriteSegmentBuilder.put()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/write-segment.html#aerospike%5Fsdk.aio.operations.query.WriteSegmentBuilder.put) | [`WriteSegmentBuilder.execute()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/write-segment.html#aerospike%5Fsdk.aio.operations.query.WriteSegmentBuilder.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.

-   [Java](#tab-panel-5398)
-   [Python](#tab-panel-5399)

```java
DataSet users = DataSet.of("test", "users");

// Creates or updates the record

session.upsert(users)

    .bins("name", "email", "age")

    .id("user-1").values("Alice Smith", "alice.smith@example.com", 29)

    .execute();
```

> 📖 **API reference**: [`Session.upsert(DataSet)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/Session.html#upsert%28com.aerospike.client.sdk.DataSet%29) | [`OperationObjectBuilder.bins(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/OperationObjectBuilder.html#bins%28java.lang.String%2Cjava.lang.String...%29) | [`IdValuesBuilder.id(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/IdValuesBuilder.html#id%28java.lang.String%29) | [`IdValuesRowBuilder.values(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/IdValuesRowBuilder.html#values%28java.lang.Object...%29) | [`ChainableQueryBuilder.execute()`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/ChainableQueryBuilder.html#execute%28%29)

```python
users = DataSet.of("test", "users")

# Creates or updates the record

await session.upsert(users.id("user-1")).put(

    {"name": "Alice Smith", "email": "alice.smith@example.com", "age": 29}

).execute()
```

> 📖 **API reference**: [`DataSet.of()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/dataset.html#aerospike%5Fsdk.dataset.DataSet.of) | [`DataSet.id()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/dataset.html#aerospike%5Fsdk.dataset.DataSet.id) | [`Session.upsert()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/session.html#aerospike%5Fsdk.aio.session.Session.upsert) | [`WriteSegmentBuilder.put()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/write-segment.html#aerospike%5Fsdk.aio.operations.query.WriteSegmentBuilder.put) | [`WriteSegmentBuilder.execute()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/write-segment.html#aerospike%5Fsdk.aio.operations.query.WriteSegmentBuilder.execute)

::: boolean bin values in verification tools
Aerospike stores booleans as integer-backed values. Some low-level tools and validation harnesses may display `true` as `1` and `false` as `0`. This is expected and does not mean the write failed.
:::

### Insert vs upsert vs other operations

| Method | Record Exists | Record Doesn’t Exist | Merges with Existing Data |
| --- | --- | --- | --- |
| `insert()` | ❌ Fails with error | ✅ Creates record | Not 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 |

The table above describes single-key behavior. Batch verbs carry the same per-verb existence semantics on the wire. `insert` requires the record to be absent, `update` requires it to exist, and so on, so per-key failures surface as non-OK rows in the returned stream.

**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:

-   [Java](#tab-panel-5400)
-   [Python](#tab-panel-5401)

```java
DataSet users = DataSet.of("test", "users");

// Record expires in 1 hour

try {

    session.upsert(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 (local time)

session.upsert(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.upsert(users.id("permanent-user"))

    .bin("name").setTo("System Admin")

    .neverExpire()

    .execute();
```

> 📖 **API reference**: [`DataSet.id(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/DataSet.html#id%28java.lang.String%29) | [`Session.upsert(DataSet)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/Session.html#upsert%28com.aerospike.client.sdk.DataSet%29) | [`OperationObjectBuilder.bins(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/OperationObjectBuilder.html#bins%28java.lang.String%2Cjava.lang.String...%29) | [`IdValuesBuilder.id(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/IdValuesBuilder.html#id%28java.lang.String%29) | [`IdValuesRowBuilder.values(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/IdValuesRowBuilder.html#values%28java.lang.Object...%29) | [`ChainableOperationBuilder.bin(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/ChainableOperationBuilder.html#bin%28java.lang.String%29) | [`ChainableQueryBuilder.execute()`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/ChainableQueryBuilder.html#execute%28%29) | [`AerospikeException`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/AerospikeException.html)

```python
users = DataSet.of("test", "users")

# Record expires in 1 hour

try:

    await session.upsert(users.id("session-token")).put(

        {"token": "abc123", "user_id": "user-1"}

    ).expire_record_after(timedelta(hours=1)).execute()

except AerospikeError as e:

    # Can fail with "Operation not allowed at this time" when TTL prerequisites are not met.

    print(f"TTL write failed: {e}")

# Record expires on 1st January, 2030 (local time)

await session.upsert(users.id("user-1")).put(

    {"name": "Alice"}

).expire_record_at(datetime(2030, 1, 1)).execute()

# Record never expires (override namespace default)

await session.upsert(users.id("permanent-user")).put(

    {"name": "System Admin"}

).never_expire().execute()
```

> 📖 **API reference**: [`DataSet.of()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/dataset.html#aerospike%5Fsdk.dataset.DataSet.of) | [`DataSet.id()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/dataset.html#aerospike%5Fsdk.dataset.DataSet.id) | [`Session.upsert()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/session.html#aerospike%5Fsdk.aio.session.Session.upsert) | [`WriteSegmentBuilder.put()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/write-segment.html#aerospike%5Fsdk.aio.operations.query.WriteSegmentBuilder.put) | [`WriteSegmentBuilder.expire_record_after()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/write-segment.html#aerospike%5Fsdk.aio.operations.query.WriteSegmentBuilder.expire%5Frecord%5Fafter) | [`WriteSegmentBuilder.expire_record_at()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/write-segment.html#aerospike%5Fsdk.aio.operations.query.WriteSegmentBuilder.expire%5Frecord%5Fat) | [`WriteSegmentBuilder.never_expire()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/write-segment.html#aerospike%5Fsdk.aio.operations.query.WriteSegmentBuilder.never%5Fexpire) | [`WriteSegmentBuilder.execute()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/write-segment.html#aerospike%5Fsdk.aio.operations.query.WriteSegmentBuilder.execute) | [`AerospikeError`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/exceptions.html#aerospike%5Fsdk.exceptions.AerospikeError)

::: ttl behavior
If you don’t specify a TTL, the record inherits the namespace’s default TTL. To keep a record from expiring, call `neverExpire()` in Java or `never_expire()` in Python.
:::
::: ttl prerequisites on the server
Per-record TTL writes depend on namespace settings. If `nsup-period` is disabled (for example `0`) and `allow-ttl-without-nsup=false`, writes using TTL methods (`expireRecordAfter(...)` in Java, `expire_record_after(...)` in Python) can fail with `Operation not allowed at this time`. Enable NSUP or update namespace settings before relying on per-record TTL in examples/tests.
:::

### Keep the existing TTL on a later write

A write that sets no TTL applies the namespace default TTL, which replaces the TTL the record already has. To change bins and leave the remaining TTL alone, call `withNoChangeInExpiration()` in Java or `with_no_change_in_expiration()` in Python:

-   [Java](#tab-panel-5402)
-   [Python](#tab-panel-5403)

```java
DataSet sessions = DataSet.of("test", "sessions");

// Write the record with a one-hour TTL

session.upsert(sessions.id("session-1"))

    .bin("token").setTo("abc123")

    .expireRecordAfterSeconds(3600)

    .execute();

// Update a bin and keep the remaining TTL

session.upsert(sessions.id("session-1"))

    .bin("last_seen").setTo(1761600000L)

    .withNoChangeInExpiration()

    .execute();

Record record = session.query(sessions.id("session-1")).execute().getFirstRecord();

System.out.println(record.bins);        // {token=abc123, last_seen=1761600000}

System.out.println(record.getTimeToLive());  // seconds left, at most 3600
```

> 📖 **API reference**: [`DataSet.id()`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/DataSet.html#id%28java.lang.String%29) | [`Session.upsert()`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/Session.html#upsert%28com.aerospike.client.sdk.Key%29) | [`ChainableOperationBuilder.expireRecordAfterSeconds()`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/ChainableOperationBuilder.html#expireRecordAfterSeconds%28int%29) | [`ChainableOperationBuilder.withNoChangeInExpiration()`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/ChainableOperationBuilder.html#withNoChangeInExpiration%28%29)

```python
sessions = DataSet.of("test", "sessions")

# Write the record with a one-hour TTL

await session.upsert(sessions.id("session-1")).put(

    {"token": "abc123"}

).expire_record_after_seconds(3600).execute()

# Update a bin and keep the remaining TTL

await session.upsert(sessions.id("session-1")).put(

    {"last_seen": 1761600000}

).with_no_change_in_expiration().execute()

row = await session.query(sessions.id("session-1")).first_or_raise()

record = row.record_or_raise()

print(record.bins)  # {'token': 'abc123', 'last_seen': 1761600000}

print(record.ttl)   # seconds left, at most 3600
```

> 📖 **API reference**: [`DataSet.id()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/dataset.html#aerospike%5Fsdk.dataset.DataSet.id) | [`Session.upsert()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/session.html#aerospike%5Fsdk.aio.session.Session.upsert) | [`WriteSegmentBuilder.expire_record_after_seconds()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/write-segment.html#aerospike%5Fsdk.aio.operations.query.WriteSegmentBuilder.expire%5Frecord%5Fafter%5Fseconds) | [`WriteSegmentBuilder.with_no_change_in_expiration()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/write-segment.html#aerospike%5Fsdk.aio.operations.query.WriteSegmentBuilder.with%5Fno%5Fchange%5Fin%5Fexpiration)

If the record has no TTL, `withNoChangeInExpiration()` and `with_no_change_in_expiration()` leave it without one, so it never expires. The [TTL prerequisites](#set-time-to-live-ttl) on the namespace still apply.

::: create-only error handling in services
For create-only flows (`insert()`), handle key-already-exists outcomes (`RecordExistsException` in Java, or `AerospikeError` with `KEY_EXISTS_ERROR` in Python) and return a domain error instead of terminating the process. This keeps request handlers and test runners repeatable across reruns.
:::

## 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, `Settings(send_key=True)` in Python.

-   [Java](#tab-panel-5404)
-   [Python](#tab-panel-5405)

```java
DataSet users = DataSet.of("test", "users");

Behavior sendKeyBehavior = Behavior.DEFAULT.deriveWithChanges("sendKey", builder ->

    builder.on(Selectors.all(), op -> op.sendKey(true)));

Session keySession = cluster.createSession(sendKeyBehavior);

keySession.upsert(users)

    .bins("name")

    .id("user-12345").values("Alice")

    .execute();

// Later, when scanning the set:

keySession.query(users)

    .execute()

    .forEach(result ->

        System.out.printf("key: %s\n", result.getKey().userKey)   // user-12345

    );
```

> 📖 **API reference**: [`Cluster.createSession(Behavior)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/Cluster.html#createSession%28com.aerospike.client.sdk.policy.Behavior%29) | [`DataSet.of(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/DataSet.html#of%28java.lang.String%2Cjava.lang.String%29) | [`Session.upsert(DataSet)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/Session.html#upsert%28com.aerospike.client.sdk.DataSet%29) | [`Session.query(DataSet)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/Session.html#query%28com.aerospike.client.sdk.DataSet%29) | [`OperationObjectBuilder.bins(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/OperationObjectBuilder.html#bins%28java.lang.String%2Cjava.lang.String...%29) | [`IdValuesBuilder.id(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/IdValuesBuilder.html#id%28java.lang.String%29) | [`IdValuesRowBuilder.values(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/IdValuesRowBuilder.html#values%28java.lang.Object...%29) | [`ChainableQueryBuilder.execute()`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/ChainableQueryBuilder.html#execute%28%29) | [`RecordStream.forEach(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/RecordStream.html#forEach%28java.util.function.Consumer%29) | [`RecordResult.getKey()`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/RecordResult.html#getKey%28%29)

```python
from aerospike_sdk.policy import Settings

users = DataSet.of("test", "users")

# send_key is a field on Settings, applied to a scope kwarg, not a bare

# keyword argument on derive_with_changes().

send_key_behavior = Behavior.DEFAULT.derive_with_changes(

    "send_key", all=Settings(send_key=True)

)

key_session = cluster.create_session(send_key_behavior)

await key_session.upsert(users.id("user-12345")).put({"name": "Alice"}).execute()

# Later, when scanning the set:

stream = await key_session.query(users).execute()

async for row in stream:

    print(row.key.value)  # "user-12345"

stream.close()
```

::: row.key.value vs record.key
The user key surfaces on the per-row envelope (`row.key`, a [`Key`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/key.html)) rather than on the bin-payload `Record`. `record.key` is `None` on a key read, and on a query it is the `Key` the server returned, which holds the user key only when it was stored. Read `row.key.value`, which works for both.
:::

> 📖 **API reference**: [`Cluster.create_session()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/cluster.html) | [`Behavior.derive_with_changes()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/behavior.html#aerospike%5Fsdk.policy.behavior.Behavior.derive%5Fwith%5Fchanges) | [`DataSet.of()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/dataset.html#aerospike%5Fsdk.dataset.DataSet.of) | [`DataSet.id()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/dataset.html#aerospike%5Fsdk.dataset.DataSet.id) | [`Behavior.DEFAULT`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/behavior.html#aerospike%5Fsdk.policy.behavior.Behavior.DEFAULT) | [`Session.query()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/session.html#aerospike%5Fsdk.aio.session.Session.query) | [`Session.upsert()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/session.html#aerospike%5Fsdk.aio.session.Session.upsert) | [`WriteSegmentBuilder.put()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/write-segment.html#aerospike%5Fsdk.aio.operations.query.WriteSegmentBuilder.put) | [`RecordResult.key`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/record-result.html#aerospike%5Fsdk.record%5Fresult.RecordResult.key) | [`RecordStream.close()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/record-stream.html#aerospike%5Fsdk.record%5Fstream.RecordStream.close) | [`QueryBuilder.execute()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/query.html#aerospike%5Fsdk.aio.operations.query.QueryBuilder.execute) | [`WriteSegmentBuilder.execute()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/write-segment.html#aerospike%5Fsdk.aio.operations.query.WriteSegmentBuilder.execute)

::: when to use send-key
Enable send-key on the behavior (`sendKey(true)` in Java, `Settings(send_key=True)` in Python) when you need to:

-   Scan records and know their original keys
-   Debug or audit record creation
-   Store human-readable identifiers alongside records
:::

## Create with CDTs

Aerospike supports lists and maps as bin values:

-   [Java](#tab-panel-5406)
-   [Python](#tab-panel-5407)

```java
DataSet users = DataSet.of("test", "users");

// List values

session.upsert(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.upsert(users.id("user-2"))

    .bin("name").setTo("Alice")

    .bin("preferences").setTo(

        Map.of("theme", "dark", "language", "en", "notifications", true))

    .execute();

// Nested structures

session.upsert(users)

    .bins("name", "address")

    .id("user-3").values(

        "Alice",

        Map.of(

            "street", "123 Main St",

            "city", "San Francisco",

            "coordinates", List.of(37.7749, -122.4194)

        )

    )

    .execute();
```

> 📖 **API reference**: [`DataSet.id(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/DataSet.html#id%28java.lang.String%29) | [`Session.upsert(DataSet)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/Session.html#upsert%28com.aerospike.client.sdk.DataSet%29) | [`OperationObjectBuilder.bins(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/OperationObjectBuilder.html#bins%28java.lang.String%2Cjava.lang.String...%29) | [`IdValuesBuilder.id(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/IdValuesBuilder.html#id%28java.lang.String%29) | [`IdValuesRowBuilder.values(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/IdValuesRowBuilder.html#values%28java.lang.Object...%29) | [`ChainableOperationBuilder.bin(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/ChainableOperationBuilder.html#bin%28java.lang.String%29) | [`BinBuilder.setTo(Map)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/BinBuilder.html#setTo%28java.util.Map%29) | [`ChainableQueryBuilder.execute()`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/ChainableQueryBuilder.html#execute%28%29)

```python
users = DataSet.of("test", "users")

# List values

await session.upsert(users.id("user-1")).put(

    {

        "name": "Alice",

        "tags": ["premium", "verified", "active"],

        "scores": [95, 87, 92, 88],

    }

).execute()

# Map/dict values

await session.upsert(users.id("user-2")).put(

    {

        "name": "Alice",

        "preferences": {

            "theme": "dark",

            "language": "en",

            "notifications": True,

        },

    }

).execute()

# Nested structures

await session.upsert(users.id("user-3")).put(

    {

        "name": "Alice",

        "address": {

            "street": "123 Main St",

            "city": "San Francisco",

            "coordinates": [37.7749, -122.4194],

        },

    }

).execute()
```

> 📖 **API reference**: [`DataSet.of()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/dataset.html#aerospike%5Fsdk.dataset.DataSet.of) | [`DataSet.id()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/dataset.html#aerospike%5Fsdk.dataset.DataSet.id) | [`Session.upsert()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/session.html#aerospike%5Fsdk.aio.session.Session.upsert) | [`WriteSegmentBuilder.put()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/write-segment.html#aerospike%5Fsdk.aio.operations.query.WriteSegmentBuilder.put) | [`WriteSegmentBuilder.execute()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/write-segment.html#aerospike%5Fsdk.aio.operations.query.WriteSegmentBuilder.execute)

> 📖 **Learn more**: [Data Model](https://aerospike.com/docs/develop/client/sdk/concepts/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:

-   [Java](#tab-panel-5408)
-   [Python](#tab-panel-5409)

```java
DataSet users = DataSet.of("test", "users");

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");

}
```

> 📖 **API reference**: [`Session.insert(DataSet)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/Session.html#insert%28com.aerospike.client.sdk.DataSet%29) | [`OperationObjectBuilder.bins(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/OperationObjectBuilder.html#bins%28java.lang.String%2Cjava.lang.String...%29) | [`IdValuesBuilder.id(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/IdValuesBuilder.html#id%28java.lang.String%29) | [`IdValuesRowBuilder.values(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/IdValuesRowBuilder.html#values%28java.lang.Object...%29) | [`ChainableQueryBuilder.execute()`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/ChainableQueryBuilder.html#execute%28%29) | [`AerospikeException`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/AerospikeException.html)

```python
users = DataSet.of("test", "users")

try:

    await session.insert(users.id("user-1")).put({"name": "Alice"}).execute()

    print("User created successfully")

except AerospikeError as e:

    if e.result_code != ResultCode.KEY_EXISTS_ERROR:

        raise

    print("User already exists, skipping creation")
```

> 📖 **API reference**: [`DataSet.of()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/dataset.html#aerospike%5Fsdk.dataset.DataSet.of) | [`DataSet.id()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/dataset.html#aerospike%5Fsdk.dataset.DataSet.id) | [`Session.insert()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/session.html#aerospike%5Fsdk.aio.session.Session.insert) | [`WriteSegmentBuilder.put()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/write-segment.html#aerospike%5Fsdk.aio.operations.query.WriteSegmentBuilder.put) | [`WriteSegmentBuilder.execute()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/write-segment.html#aerospike%5Fsdk.aio.operations.query.WriteSegmentBuilder.execute)

> 📖 **Learn more**: [Error Handling](https://aerospike.com/docs/develop/client/sdk/concepts/errors) covers all exception types.

## Batch create

For creating multiple records efficiently, see [Batch Operations](https://aerospike.com/docs/develop/client/sdk/usage/batch).

-   [Java](#tab-panel-5410)
-   [Python](#tab-panel-5411)

```java
DataSet users = DataSet.of("test", "users");

// 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();
```

> 📖 **API reference**: [`Session.insert(DataSet)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/Session.html#insert%28com.aerospike.client.sdk.DataSet%29) | [`OperationObjectBuilder.bins(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/OperationObjectBuilder.html#bins%28java.lang.String%2Cjava.lang.String...%29) | [`IdValuesBuilder.id(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/IdValuesBuilder.html#id%28java.lang.String%29) | [`IdValuesRowBuilder.values(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/IdValuesRowBuilder.html#values%28java.lang.Object...%29) | [`ChainableQueryBuilder.execute()`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/ChainableQueryBuilder.html#execute%28%29)

```python
users = DataSet.of("test", "users")

# Quick preview - see Batch Operations for full details

await (

    session.insert(users)

    .bins("name")

    .row("user-1", "Alice")

    .row("user-2", "Bob")

    .row("user-3", "Carol")

    .execute()

)
```

> 📖 **API reference**: [`DataSet.of()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/dataset.html#aerospike%5Fsdk.dataset.DataSet.of) | [`Session.insert()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/session.html#aerospike%5Fsdk.aio.session.Session.insert) | [`DataSetWriteBuilder.bins()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/row-write.html#aerospike%5Fsdk.aio.operations.query.DataSetWriteBuilder.bins) | [`RowWriteBuilder.row()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/row-write.html#aerospike%5Fsdk.aio.operations.query.RowWriteBuilder.row) | [`RowWriteBuilder.execute()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/row-write.html#aerospike%5Fsdk.aio.operations.query.RowWriteBuilder.execute)

Each key in the batch carries its own payload, and the whole set travels in one round trip: `bins(...)` fixes the column schema once, then each `row(id, *values)` supplies one record’s ID and values in that order. The row count doesn’t need to match across different writes, but the value count in every `row(...)` call must match the number of names passed to `bins(...)`.

Batch **reads** and batch **deletes** are also available: pass several keys to one command with [`DataSet.ids()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/dataset.html#aerospike%5Fsdk.dataset.DataSet.ids).

## Complete example

This example is self-contained—it lists every import needed to run standalone.

-   [Java](#tab-panel-5412)
-   [Python](#tab-panel-5413)

```java
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**: [`ClusterDefinition(String,int)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/ClusterDefinition.html#%3Cinit%3E%28java.lang.String%2Cint%29) | [`ClusterDefinition.connect()`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/ClusterDefinition.html#connect%28%29) | [`Cluster.createSession(Behavior)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/Cluster.html#createSession%28com.aerospike.client.sdk.policy.Behavior%29) | [`Cluster.close()`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/Cluster.html#close%28%29) | [`DataSet.of(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/DataSet.html#of%28java.lang.String%2Cjava.lang.String%29) | [`Session.insert(DataSet)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/Session.html#insert%28com.aerospike.client.sdk.DataSet%29) | [`Session.upsert(DataSet)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/Session.html#upsert%28com.aerospike.client.sdk.DataSet%29) | [`Session.delete(Key)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/Session.html#delete%28com.aerospike.client.sdk.Key%29) | [`OperationObjectBuilder.bins(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/OperationObjectBuilder.html#bins%28java.lang.String%2Cjava.lang.String...%29) | [`IdValuesBuilder.id(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/IdValuesBuilder.html#id%28java.lang.String%29) | [`IdValuesRowBuilder.values(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/IdValuesRowBuilder.html#values%28java.lang.Object...%29) | [`ChainableQueryBuilder.execute()`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/ChainableQueryBuilder.html#execute%28%29)

```python
import asyncio

from aerospike_sdk import Behavior, ClusterDefinition, DataSet

async def main():

    async with ClusterDefinition("localhost", 3000).connect() as cluster:

        session = cluster.create_session(Behavior.DEFAULT)

        users = DataSet.of("test", "users")

        key = users.id("create-example-user")

        # Cleanup so the example is repeatable.

        await session.delete(key).execute()

        # Simple insert

        await session.insert(key).put(

            {"name": "Alice Smith", "email": "alice@example.com", "age": 28}

        ).execute()

        # Upsert with complex data

        await session.upsert(key).put(

            {

                "name": "Alice Smith",

                "tags": ["premium", "verified"],

                "preferences": {"theme": "dark"},

            }

        ).execute()

        print("Records created successfully!")

if __name__ == "__main__":

    asyncio.run(main())
```

> 📖 **API reference**: [`ClusterDefinition`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/cluster-definition.html) | [`ClusterDefinition.connect()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/cluster-definition.html) | [`Cluster.create_session()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/cluster.html) | [`DataSet.of()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/dataset.html#aerospike%5Fsdk.dataset.DataSet.of) | [`DataSet.id()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/dataset.html#aerospike%5Fsdk.dataset.DataSet.id) | [`Behavior.DEFAULT`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/behavior.html#aerospike%5Fsdk.policy.behavior.Behavior.DEFAULT) | [`Session.upsert()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/session.html#aerospike%5Fsdk.aio.session.Session.upsert) | [`Session.insert()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/session.html#aerospike%5Fsdk.aio.session.Session.insert) | [`Session.delete()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/session.html#aerospike%5Fsdk.aio.session.Session.delete) | [`WriteSegmentBuilder.put()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/write-segment.html#aerospike%5Fsdk.aio.operations.query.WriteSegmentBuilder.put) | [`WriteSegmentBuilder.execute()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/write-segment.html#aerospike%5Fsdk.aio.operations.query.WriteSegmentBuilder.execute)

## API reference summary

| Method | Description |
| --- | --- |
| `insert()` | Create a new record (fails if exists) |
| `upsert()` | Create or update a record |
| `.bins(name1, name2, ...).id(...).values(...)` (Java) · `.put({...})` or `.bins(...).row(id, ...)` (Python) | Set bin values |
| `.expireRecordAfter(duration)` (Java) · `.expire_record_after(timedelta)` or `.expire_record_after_seconds(seconds)` (Python) | Set time-to-live |
| `.expireRecordAt(localDateTime)` (Java) · `.expire_record_at(datetime)` (Python) | Expire records at a wall-clock time |
| `.neverExpire()` (Java) · `.never_expire()` (Python) | Pin record TTL to never expire |

## Next steps

Read Records

Retrieve the records you’ve created.

[Read Records →](https://aerospike.com/docs/develop/client/sdk/usage/read)

Update Records

Modify existing records and bins.

[Update Records →](https://aerospike.com/docs/develop/client/sdk/usage/update)

Batch Operations

Create multiple records efficiently.

[Batch Operations →](https://aerospike.com/docs/develop/client/sdk/usage/batch)

Data Model

Understand namespaces, sets, and bins.

[Data Model →](https://aerospike.com/docs/develop/client/sdk/concepts/data-model)