Skip to content

Python sync API

For the complete documentation index see: llms.txt

All documentation pages available in markdown.

The Aerospike Python SDK provides a synchronous API for applications that do not use asyncio. Use SyncClient for scripts, CLIs, batch jobs, and other blocking code paths. The fluent builder surface matches the async API: chain methods on a session, then call .execute().

Applies to

  • Aerospike Developer SDK preview (Python 3.10+)
  • Package: aerospike-sdk
  • Aerospike Database 6.0 or later unless a section states otherwise

Prerequisites

The Python SDK supports Python 3.10 and later. For best performance, use Python 3.14 or later to take advantage of free-threading and other runtime improvements in the 3.14 series. See the Python 3.14 release notes for details.

Async vs sync

APIEntry pointBest for
AsyncClientWeb servers, workers, and other asyncio applications
SyncSyncClientScripts, CLIs, and code without an event loop

The synchronous API mirrors the async surface. Drop async/await, use a regular with statement for the client, and iterate query results with a standard for loop instead of async for. Shared types such as DataSet and Behavior work the same in both APIs.

Key concepts

ConceptRole
SyncClientConnects to the cluster and manages the connection lifecycle
SyncSessionExecutes reads and writes using a chosen behavior (timeouts, retries, consistency)
DataSetNamespace and set pair; use .id(key) to build record keys
SyncQueryBuilderConfigures reads; call .execute() to get a RecordStream
SyncWriteSegmentBuilderConfigures writes; chain bin operations, then call .execute()

Connect and create a session

Open a client with a context manager so the connection closes automatically:

from aerospike_sdk import Behavior, DataSet, SyncClient
with SyncClient("localhost:3000") as client:
session = client.create_session(Behavior.DEFAULT)
users = DataSet.of("test", "users")
# Use session for reads and writes...

📖 API reference: SyncClient | SyncClient.create_session() | Behavior.DEFAULT | DataSet.of()

For TLS, authentication, and advanced cluster configuration, see Connect to Aerospike and the Python SDK connecting guide.

Create records

Write operations start on SyncSession and return a SyncWriteSegmentBuilder. Chain bin methods, then call .execute().

Upsert (create or update)

Use upsert() when the record may or may not already exist:

with SyncClient("localhost:3000") as client:
session = client.create_session(Behavior.DEFAULT)
users = DataSet.of("test", "users")
session.upsert(users.id("user-1")).bin("name").set_to("Alice").bin("age").set_to(30).execute()

You can also set multiple bins at once with .put():

session.upsert(users.id("user-1")).put(
{"name": "Alice", "email": "alice@example.com", "status": "active", "age": 30}
).execute()

Insert (create only)

Use insert() when the record must not already exist. The call fails if the key is taken:

session.insert(users.id("user-2")).put({"name": "Bob", "age": 25}).execute()

📖 API reference: SyncSession.upsert() | SyncSession.insert() | SyncWriteSegmentBuilder.set_to() | SyncWriteSegmentBuilder.put() | SyncWriteSegmentBuilder.execute()

See Create records for TTL, batch creation, and collection data types.

Read records

Reads go through session.query(), which returns a SyncQueryBuilder. Call .execute() to get a stream of RecordResult objects.

Point read (single key)

with SyncClient("localhost:3000") as client:
session = client.create_session(Behavior.DEFAULT)
users = DataSet.of("test", "users")
stream = session.query(users.id("user-1")).execute()
result = stream.first_or_raise()
print(result.record.bins) # {'name': 'Alice', 'age': 30, ...}
stream.close()

Query with an AEL filter

Filter records server-side with Aerospike Expression Language (AEL):

stream = session.query(users).where("$.status == 'active' and $.age > 21").execute()
for result in stream:
print(result.record.bins)
stream.close()

Return only specific bins to reduce network transfer:

stream = session.query(users.id("user-1")).bins(["name", "email"]).execute()
result = stream.first_or_raise()
print(result.record.bins)
stream.close()

📖 API reference: SyncSession.query() | SyncQueryBuilder.where() | SyncQueryBuilder.bins() | SyncQueryBuilder.execute() | RecordStream.first_or_raise()

See Read records and Query by field values for batch reads, partition filters, and query policies.

Modify records

Use update() when the record must already exist. Chain bin operations on SyncWriteSegmentBuilder, then call .execute().

  1. Update a bin value.

    with SyncClient("localhost:3000") as client:
    session = client.create_session(Behavior.DEFAULT)
    users = DataSet.of("test", "users")
    session.update(users.id("user-1")).bin("email").set_to("alice.smith@example.com").execute()
  2. Increment a numeric bin.

    session.update(users.id("user-1")).bin("login_count").increment_by(1).execute()
  3. Apply a server-side filter so only matching records are updated.

    session.update(users.id("user-1")).where("$.age >= 18").bin("verified").set_to(True).execute()
  4. Replace all bins.

    replace() writes the bins you specify. The record is created if it does not already exist; existing bins not in the write are removed.

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

    Use replace_if_exists() if you require the record to already exist.

📖 API reference: SyncSession.update() | SyncSession.replace() | SyncWriteSegmentBuilder.increment_by() | SyncWriteSegmentBuilder.where()

See Update records and the Python SDK writing guide for conditional writes, generation checks, TTL, and batch updates.

Delete records

Remove a single key:

session.delete(users.id("user-1")).execute()

See Delete records for durable delete and batch deletion patterns.

Complete example

The script below connects to a local cluster, creates two records, reads them back, updates one record, and cleans up. Save it as sync_example.py and run it against a cluster on localhost:3000:

Terminal window
python sync_example.py
from aerospike_sdk import Behavior, DataSet, SyncClient
def main() -> None:
with SyncClient("localhost:3000") as client:
session = client.create_session(Behavior.DEFAULT)
users = DataSet.of("test", "users")
# Cleanup from prior runs so the script is repeatable.
for user_id in ("user-1", "user-2"):
session.delete(users.id(user_id)).execute()
# Create: upsert the first user.
session.upsert(users.id("user-1")).put(
{
"name": "Alice",
"email": "alice@example.com",
"status": "active",
"age": 30,
"login_count": 0,
}
).execute()
# Create: insert a second user (fails if the key already exists).
session.insert(users.id("user-2")).put(
{"name": "Bob", "age": 25, "status": "active"}
).execute()
# Read: point read by key.
stream = session.query(users.id("user-1")).execute()
user = stream.first_or_raise().record
print(f"User 1: {user.bins}")
stream.close()
# Read: query active users over 21 with AEL.
stream = session.query(users).where("$.status == 'active' and $.age > 21").execute()
print("Active users over 21:")
for result in stream:
print(f" - {result.record.bins.get('name')}")
stream.close()
# Modify: update email, increment a counter, and set a conditional flag.
session.update(users.id("user-1")).bin("email").set_to("alice.smith@example.com").execute()
session.update(users.id("user-1")).bin("login_count").increment_by(1).execute()
session.update(users.id("user-1")).where("$.age >= 18").bin("verified").set_to(True).execute()
# Read back selected bins.
stream = session.query(users.id("user-1")).bins(["name", "email", "login_count", "verified"]).execute()
updated = stream.first_or_raise().record
print(f"Updated user 1: {updated.bins}")
stream.close()
# Cleanup.
session.delete(users.id("user-1")).execute()
session.delete(users.id("user-2")).execute()
print("Done.")
if __name__ == "__main__":
main()

Expected output (bin order may vary):

User 1: {'name': 'Alice', 'email': 'alice@example.com', 'status': 'active', 'age': 30, 'login_count': 0}
Active users over 21:
- Alice
Updated user 1: {'name': 'Alice', 'email': 'alice.smith@example.com', 'login_count': 1, 'verified': True}
Done.

Next steps

Quickstart

Run a complete end-to-end example in under 5 minutes.

Quickstart →

Python SDK docs

Full guides and sync API reference on Read the Docs.

Python SDK →

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?