---
title: "Query records"
description: "Query and filter Aerospike records using AEL expressions in the Java and Python Developer SDKs."
---

# Query 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 find records in Aerospike using the Developer SDK’s AEL (Aerospike Expression Language) queries. AEL provides a readable, SQL-like syntax for filtering data.

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-5462)
-   [Python](#tab-panel-5463)

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

import com.aerospike.client.sdk.Key;

import com.aerospike.client.sdk.Record;

import com.aerospike.client.sdk.RecordResult;

import com.aerospike.client.sdk.RecordStream;

import java.util.ArrayList;

import java.util.List;

import java.util.Map;

import java.util.concurrent.atomic.AtomicBoolean;

import java.util.concurrent.atomic.AtomicInteger;

import java.util.concurrent.atomic.AtomicLong;
```

```python
from aerospike_sdk import DataSet
```

## Basic query

All operations which read data are queries, regardless of whether you are reading one record, 100 records, or performing an index query. Use `query()` to find records, and a `where` clause to provide filtering if desired:

-   [Java](#tab-panel-5464)
-   [Python](#tab-panel-5465)

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

RecordStream stream = session.query(users)

    .where("$.status == 'active'")

    .execute();

stream.forEach(result -> {

    Record user = result.recordOrThrow();

    System.out.println("Name: " + user.getString("name"));

});
```

> 📖 **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.query(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/Session.html#query%28com.aerospike.client.sdk.DataSet%29) | [`ChainableQueryBuilder.where(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/ChainableQueryBuilder.html#where%28java.lang.String%2Cjava.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.recordOrThrow()`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/RecordResult.html#recordOrThrow%28%29) | [`Record.getString(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/Record.html#getString%28java.lang.String%29)

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

stream = await session.query(users).where("$.status == 'active'").execute()

async for row in stream:

    record = row.record_or_raise()

    print(f"Name: {record.bins['name']}")

stream.close()
```

> 📖 **API reference**: [`DataSet.of()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/dataset.html#aerospike%5Fsdk.dataset.DataSet.of) | [`Session.query()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/session.html#aerospike%5Fsdk.aio.session.Session.query) | [`QueryBuilder.where()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/query.html#aerospike%5Fsdk.aio.operations.query.QueryBuilder.where) | [`QueryBuilder.execute()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/query.html#aerospike%5Fsdk.aio.operations.query.QueryBuilder.execute) | [`RecordStream.close()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/record-stream.html#aerospike%5Fsdk.record%5Fstream.RecordStream.close) | [`RecordResult.record_or_raise()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/record-result.html#aerospike%5Fsdk.record%5Fresult.RecordResult.record%5For%5Fraise) | [`RecordStream.close()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/record-stream.html#aerospike%5Fsdk.record%5Fstream.RecordStream.close)

## AEL operators

Use `$.binName` to get the contents of a bin called `binName`. String literals can be in either single or double quotes. Floats are numbers with a decimal point and integers are just digits.

### Comparison operators

| Operator | Description | Example |
| --- | --- | --- |
| `==` | Equal | `"$.status == 'active'"` |
| `!=` | Not equal | `"$.status != 'inactive'"` |
| `>` | Greater than | `"$.age > 21"` |
| `>=` | Greater than or equal | `"$.age >= 18"` |
| `<` | Less than | `"$.balance < 0"` |
| `<=` | Less than or equal | `"$.score <= 100"` |

See [AEL operators](https://aerospike.com/docs/develop/client/sdk/concepts/ael/reference/operators) for a complete list of AEL operators.

-   [Java](#tab-panel-5466)
-   [Python](#tab-panel-5467)

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

// Numeric comparisons

RecordStream s1 = session.query(users).where("$.age >= 18").execute();

s1.forEach((RecordResult result) -> { /* use result.recordOrThrow() */ });

// String equality

RecordStream s2 = session.query(users).where("$.role == 'admin'").execute();

s2.forEach((RecordResult result) -> { /* ... */ });

// Not equal

RecordStream s3 = session.query(users).where("$.deleted != true").execute();

s3.forEach((RecordResult result) -> { /* ... */ });
```

> 📖 **API reference**: [`Session.query(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/Session.html#query%28com.aerospike.client.sdk.DataSet%29) | [`ChainableQueryBuilder.where(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/ChainableQueryBuilder.html#where%28java.lang.String%2Cjava.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.recordOrThrow()`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/RecordResult.html#recordOrThrow%28%29)

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

# Numeric comparisons

s1 = await session.query(users).where("$.age >= 18").execute()

async for row in s1:

    pass  # use row.record_or_raise()

s1.close()

# String equality

s2 = await session.query(users).where("$.role == 'admin'").execute()

async for row in s2:

    pass  # ...

s2.close()

# Not equal

s3 = await session.query(users).where("$.deleted != true").execute()

async for row in s3:

    pass  # ...

s3.close()
```

> 📖 **API reference**: [`DataSet.of()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/dataset.html#aerospike%5Fsdk.dataset.DataSet.of) | [`Session.query()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/session.html#aerospike%5Fsdk.aio.session.Session.query) | [`QueryBuilder.where()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/query.html#aerospike%5Fsdk.aio.operations.query.QueryBuilder.where) | [`QueryBuilder.execute()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/query.html#aerospike%5Fsdk.aio.operations.query.QueryBuilder.execute) | [`RecordStream.close()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/record-stream.html#aerospike%5Fsdk.record%5Fstream.RecordStream.close)

### Logical operators

Combine conditions with `and`, `or`, and `not`:

-   [Java](#tab-panel-5468)
-   [Python](#tab-panel-5469)

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

// AND

RecordStream a = session.query(users)

    .where("$.status == 'active' and $.age >= 18")

    .execute();

a.forEach((RecordResult result) -> { /* ... */ });

// OR

RecordStream b = session.query(users)

    .where("$.role == 'admin' or $.role == 'moderator'")

    .execute();

b.forEach((RecordResult result) -> { /* ... */ });

// NOT

RecordStream c = session.query(users)

    .where("not($.status == 'banned')")

    .execute();

c.forEach((RecordResult result) -> { /* ... */ });

// Complex combinations

RecordStream d = session.query(users)

    .where("($.status == 'active' or $.status == 'pending') and $.age >= 18")

    .execute();

d.forEach((RecordResult result) -> { /* ... */ });
```

> 📖 **API reference**: [`Session.query(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/Session.html#query%28com.aerospike.client.sdk.DataSet%29) | [`ChainableQueryBuilder.where(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/ChainableQueryBuilder.html#where%28java.lang.String%2Cjava.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.recordOrThrow()`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/RecordResult.html#recordOrThrow%28%29)

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

# AND

a = await session.query(users).where("$.status == 'active' and $.age >= 18").execute()

async for row in a:

    pass  # use row.record_or_raise()

a.close()

# OR

b = await session.query(users).where("$.role == 'admin' or $.role == 'moderator'").execute()

async for row in b:

    pass  # ...

b.close()

# NOT

c = await session.query(users).where("not($.status == 'banned')").execute()

async for row in c:

    pass  # ...

c.close()

# Complex combinations

d = await session.query(users).where(

    "($.status == 'active' or $.status == 'pending') and $.age >= 18"

).execute()

async for row in d:

    pass  # ...

d.close()
```

> 📖 **API reference**: [`DataSet.of()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/dataset.html#aerospike%5Fsdk.dataset.DataSet.of) | [`Session.query()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/session.html#aerospike%5Fsdk.aio.session.Session.query) | [`QueryBuilder.where()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/query.html#aerospike%5Fsdk.aio.operations.query.QueryBuilder.where) | [`QueryBuilder.execute()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/query.html#aerospike%5Fsdk.aio.operations.query.QueryBuilder.execute) | [`RecordStream.close()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/record-stream.html#aerospike%5Fsdk.record%5Fstream.RecordStream.close)

### Membership and existence operators

| Operator | Description | Example |
| --- | --- | --- |
| `in` | Membership in a list | `"'admin' in $.roles"` |
| `exists()` | Path/bin existence check | `"$.email.exists()"` |
| `count()` | Collection cardinality. Pin the container type with `:LIST` or `:MAP` | `"$.tags:LIST.count() > 3"` |

-   [Java](#tab-panel-5470)
-   [Python](#tab-panel-5471)

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

// Membership in list

RecordStream s1 = session.query(users)

    .where("'admin' in $.roles")

    .execute();

s1.forEach((RecordResult result) -> { /* ... */ });

// Exists tests for the presence of the bin in the record

RecordStream s2 = session.query(users)

    .where("$.email.exists()")

    .execute();

s2.forEach((RecordResult result) -> { /* ... */ });

// Collection size

RecordStream s3 = session.query(users)

    .where("$.tags:LIST.count() > 3")

    .execute();

s3.forEach((RecordResult result) -> { /* ... */ });
```

> 📖 **API reference**: [`Session.query(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/Session.html#query%28com.aerospike.client.sdk.DataSet%29) | [`ChainableQueryBuilder.where(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/ChainableQueryBuilder.html#where%28java.lang.String%2Cjava.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.recordOrThrow()`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/RecordResult.html#recordOrThrow%28%29)

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

# Membership in list

s1 = await session.query(users).where("'admin' in $.roles").execute()

async for row in s1:

    pass  # use row.record_or_raise()

s1.close()

# Exists tests for the presence of the bin in the record

s2 = await session.query(users).where("$.email.exists()").execute()

async for row in s2:

    pass  # ...

s2.close()

# Collection size

s3 = await session.query(users).where("$.tags:LIST.count() > 3").execute()

async for row in s3:

    pass  # ...

s3.close()
```

> 📖 **API reference**: [`DataSet.of()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/dataset.html#aerospike%5Fsdk.dataset.DataSet.of) | [`Session.query()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/session.html#aerospike%5Fsdk.aio.session.Session.query) | [`QueryBuilder.where()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/query.html#aerospike%5Fsdk.aio.operations.query.QueryBuilder.where) | [`QueryBuilder.execute()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/query.html#aerospike%5Fsdk.aio.operations.query.QueryBuilder.execute) | [`RecordStream.close()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/record-stream.html#aerospike%5Fsdk.record%5Fstream.RecordStream.close)

## Select specific bins

Return only the bins you need:

-   [Java](#tab-panel-5472)
-   [Python](#tab-panel-5473)

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

RecordStream stream = session.query(users)

    .where("$.status == 'active'")

    .readingOnlyBins("name", "email")  // Only return name and email

    .execute();

stream.forEach((RecordResult result) -> {

    Record user = result.recordOrThrow();

    System.out.println(user.getString("name"));

});
```

> 📖 **API reference**: [`Session.query(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/Session.html#query%28com.aerospike.client.sdk.DataSet%29) | [`ChainableQueryBuilder.where(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/ChainableQueryBuilder.html#where%28java.lang.String%2Cjava.lang.Object...%29) | [`ChainableQueryBuilder.readingOnlyBins(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/ChainableQueryBuilder.html#readingOnlyBins%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) | [`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.recordOrThrow()`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/RecordResult.html#recordOrThrow%28%29) | [`Record.getString(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/Record.html#getString%28java.lang.String%29)

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

stream = await (

    session.query(users)

    .where("$.status == 'active'")

    .bins(["name", "email"])

    .execute()

)

async for row in stream:

    record = row.record_or_raise()

    print(record.bins["name"])

stream.close()
```

> 📖 **API reference**: [`DataSet.of()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/dataset.html#aerospike%5Fsdk.dataset.DataSet.of) | [`Session.query()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/session.html#aerospike%5Fsdk.aio.session.Session.query) | [`QueryBuilder.where()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/query.html#aerospike%5Fsdk.aio.operations.query.QueryBuilder.where) | [`QueryBuilder.bins()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/query.html#aerospike%5Fsdk.aio.operations.query.QueryBuilder.bins) | [`QueryBuilder.execute()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/query.html#aerospike%5Fsdk.aio.operations.query.QueryBuilder.execute) | [`RecordResult.record_or_raise()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/record-result.html#aerospike%5Fsdk.record%5Fresult.RecordResult.record%5For%5Fraise) | [`RecordStream.close()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/record-stream.html#aerospike%5Fsdk.record%5Fstream.RecordStream.close)

## Limit results

Limit the number of records returned:

-   [Java](#tab-panel-5474)
-   [Python](#tab-panel-5475)

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

// Get first 10 active users

RecordStream stream = session.query(users)

    .where("$.status == 'active'")

    .limit(10)

    .execute();

stream.forEach((RecordResult result) -> { /* ... */ });
```

> 📖 **API reference**: [`Session.query(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/Session.html#query%28com.aerospike.client.sdk.DataSet%29) | [`ChainableQueryBuilder.where(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/ChainableQueryBuilder.html#where%28java.lang.String%2Cjava.lang.Object...%29) | [`ChainableQueryBuilder.limit(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/ChainableQueryBuilder.html#limit%28long%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.recordOrThrow()`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/RecordResult.html#recordOrThrow%28%29)

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

# Get first 10 active users

stream = await (

    session.query(users)

    .where("$.status == 'active'")

    .limit(10)

    .execute()

)

async for row in stream:

    pass  # use row.record_or_raise()

stream.close()
```

> 📖 **API reference**: [`DataSet.of()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/dataset.html#aerospike%5Fsdk.dataset.DataSet.of) | [`Session.query()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/session.html#aerospike%5Fsdk.aio.session.Session.query) | [`QueryBuilder.where()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/query.html#aerospike%5Fsdk.aio.operations.query.QueryBuilder.where) | [`QueryBuilder.limit()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/query.html#aerospike%5Fsdk.aio.operations.query.QueryBuilder.limit) | [`QueryBuilder.execute()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/query.html#aerospike%5Fsdk.aio.operations.query.QueryBuilder.execute) | [`RecordStream.close()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/record-stream.html#aerospike%5Fsdk.record%5Fstream.RecordStream.close)

## Paginate large result sets

`limit(n)` caps the _total_ records returned, but it doesn’t control how many round trips the server does to get there. For large queries, the Developer SDK exposes server-side chunking so you can bound how much is fetched per round trip and drive the next chunk explicitly:

-   [Java](#tab-panel-5476)
-   [Python](#tab-panel-5477)

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

RecordStream stream = session.query(users).chunkSize(100).execute();

try {

    while (stream.hasMoreChunks()) {

        while (stream.hasNext()) {

            Record record = stream.next().recordOrThrow();

            System.out.println(record.getString("name"));

        }

    }

} finally {

    stream.close();

}
```

> 📖 **API reference**: [`BaseQueryBuilder.chunkSize(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/query/BaseQueryBuilder.html#chunkSize%28int%29) | [`RecordStream.hasMoreChunks()`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/RecordStream.html#hasMoreChunks%28%29) | [`RecordStream.hasNext()`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/RecordStream.html#hasNext%28%29) | [`RecordStream.next()`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/RecordStream.html#next%28%29) | [`RecordResult.recordOrThrow()`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/RecordResult.html#recordOrThrow%28%29)

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

stream = await session.query(users).chunk_size(100).execute()

try:

    while await stream.has_more_chunks():

        async for row in stream:

            record = row.record_or_raise()

            print(record.bins["name"])

finally:

    stream.close()
```

> 📖 **API reference**: [`QueryBuilder.chunk_size()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/query.html#aerospike%5Fsdk.aio.operations.query.QueryBuilder.chunk_size) | [`RecordStream.has_more_chunks()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/record-stream.html#aerospike%5Fsdk.record%5Fstream.RecordStream.has%5Fmore%5Fchunks)

::: caution
`hasMoreChunks()` / `has_more_chunks()` must drive the outer loop. Iterating the stream without it (`forEach` in Java, `async for` in Python) only consumes the first chunk (`chunkSize` / `chunk_size` records) and silently stops, and the rest of the result set is never fetched.
:::

`chunkSize` / `chunk_size` bounds client memory and round-trip size, and `limit` bounds the total record count. Combine them to page through a large query a fixed number of records at a time while still capping the overall result.

### Throttle query rate

To avoid overloading the cluster with a large background query, cap how many records per second each server node streams back:

-   [Java](#tab-panel-5478)
-   [Python](#tab-panel-5479)

```java
RecordStream stream = session.query(users).recordsPerSecond(1000).execute();

stream.forEach(result -> {

    // process at the throttled rate

});
```

> 📖 **API reference**: [`IndexBasedQueryBuilderInterface.recordsPerSecond(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/query/IndexBasedQueryBuilderInterface.html#recordsPerSecond%28int%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)

```python
stream = await session.query(users).records_per_second(1000).execute()

async for row in stream:

    ...  # process at the throttled rate

stream.close()
```

> 📖 **API reference**: [`QueryBuilder.records_per_second()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/query.html#aerospike%5Fsdk.aio.operations.query.QueryBuilder.records%5Fper%5Fsecond)

`recordsPerSecond(0)` / `records_per_second(0)` (the default) is unthrottled.

### Sort results

There is no server-side `ORDER BY` for queries: secondary indexes answer “which records match,” not “in what order.” To return sorted, paginated results (for example, 5 records per page sorted by `name`), collect the matching records and sort them client-side, then page through the sorted list. Java wraps the result set in a `NavigatableRecordStream` that sorts and pages for you. Python sorts the collected records and slices them:

-   [Java](#tab-panel-5480)
-   [Python](#tab-panel-5481)

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

NavigatableRecordStream pages = session.query(users)

    .where("$.status == 'active'")

    .execute()

    .asNavigatableStream()

    .sortBy("name")

    .pageSize(5);

while (pages.hasMorePages()) {

    while (pages.hasNext()) {

        Record user = pages.next().recordOrThrow();

        System.out.println(user.getString("name"));

    }

}
```

> 📖 **API reference**: [`RecordStream.asNavigatableStream()`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/RecordStream.html#asNavigatableStream%28%29) | [`NavigatableRecordStream.sortBy(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/NavigatableRecordStream.html#sortBy%28java.lang.String%29) | [`NavigatableRecordStream.pageSize(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/NavigatableRecordStream.html#pageSize%28int%29) | [`NavigatableRecordStream.hasMorePages()`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/NavigatableRecordStream.html#hasMorePages%28%29)

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

stream = await session.query(users).where("$.status == 'active'").execute()

records = [row.record_or_raise() async for row in stream]

records.sort(key=lambda r: r.bins["name"])

page_size = 5

page_1 = records[0:page_size]

page_2 = records[page_size : page_size * 2]
```

> 📖 **API reference**: [`RecordResult.record_or_raise()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/record-result.html#aerospike%5Fsdk.record%5Fresult.RecordResult.record%5For%5Fraise)

Both approaches hold the full result set in memory. For very large sets, narrow the query first with `where(...)` and `limit(...)`, or maintain a separately indexed sort order (for example, a bin you can run a range query against) instead of sorting the full result set on every request.

## Stream results

The record streams buffer results returned from the server efficiently when queries which return large numbers of results are executed. This is transparent to the API, but it means that large result sets are not loaded into memory in their entirety.

Record streams should be closed when finished, freeing up resources on both the client side and server side. In Java, terminal helpers such as `getFirst`, `getFirstRecord`, and `forEach` close the stream when the call finishes. In Python, fully consuming a stream closes it automatically: iterating to completion with `async for`, or calling `collect()` or `failures()`, drains and releases the stream. `first()` and `first_or_raise()` take the first result and close the stream; `pop()` and `pop_or_raise()` take one result and leave the stream open. When you abandon a stream partway through, call `stream.close()` (or wrap the work in a `try` / `finally`) to release client and server resources promptly.

For large result sets, stream records instead of loading all into memory:

-   [Java](#tab-panel-5482)
-   [Python](#tab-panel-5483)

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

// Process records one at a time

RecordStream stream = session.query(users)

    .where("$.status == 'active'")

    .execute();

stream.forEach((RecordResult result) -> {

    if (result.isOk()) {

        Record user = result.recordOrThrow();

        if (user != null) {

            System.out.println("Processing: " + user.getString("name"));

        }

    }

});
```

> 📖 **API reference**: [`Session.query(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/Session.html#query%28com.aerospike.client.sdk.DataSet%29) | [`ChainableQueryBuilder.where(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/ChainableQueryBuilder.html#where%28java.lang.String%2Cjava.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.isOk()`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/RecordResult.html#isOk%28%29) | [`RecordResult.recordOrThrow()`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/RecordResult.html#recordOrThrow%28%29) | [`Record.getString(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/Record.html#getString%28java.lang.String%29)

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

# Process records one at a time

stream = await session.query(users).where("$.status == 'active'").execute()

async for row in stream:

    record = row.record_or_raise()

    print(f"Processing: {record.bins['name']}")

stream.close()

# Equivalent with try/finally — guarantees close on exception:

stream = await session.query(users).where("$.status == 'active'").execute()

try:

    async for row in stream:

        record = row.record_or_raise()

        print(f"Processing: {record.bins['name']}")

finally:

    stream.close()
```

> 📖 **API reference**: [`DataSet.of()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/dataset.html#aerospike%5Fsdk.dataset.DataSet.of) | [`Session.query()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/session.html#aerospike%5Fsdk.aio.session.Session.query) | [`QueryBuilder.where()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/query.html#aerospike%5Fsdk.aio.operations.query.QueryBuilder.where) | [`RecordResult.record_or_raise()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/record-result.html#aerospike%5Fsdk.record%5Fresult.RecordResult.record%5For%5Fraise) | [`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)

## Iteration patterns and key access

-   [Java](#tab-panel-5490)
-   [Python](#tab-panel-5491)

### Accessing the record key

The `Record` class holds only bin data (`bins`, `generation`, `expiration`). The key is on the `RecordResult` wrapper, accessible via `result.getKey()`:

```java
stream.forEach(result -> {

    Key k = result.getKey();

    // String key:

    String strKey = k.userKey.toString();

    // Integer key (userKey is a Value; call toLong()):

    long intKey = k.userKey.toLong();

    Record record = result.recordOrThrow();

    // use record.getString("name"), record.getInt("age"), etc.

});
```

`record.key` and `record.getKey()` do not exist. Always use `result.getKey()` on the `RecordResult`, not on the `Record` itself.

::: userkey may be null in query results
`k.userKey` is only non-null when the user key was stored with the record at write time. Records written by external tooling, older clients, or any write that does not enable key storage will have `k.userKey == null`. Calling `.toString()` or `.toLong()` on a null `userKey` throws a `NullPointerException`.

Always guard `userKey` access before using it:

```java
stream.forEach(result -> {

    Key k = result.getKey();

    // userKey is null if the key was not stored with the record

    String strKey = (k.userKey != null) ? k.userKey.toString() : null;

    if (strKey != null && strKey.startsWith("prefix-")) {

        Record record = result.recordOrThrow();

        // process record ...

    }

});
```
:::

### Accessing bins on a `Record`

`Record` exposes typed getters (`getString`, `getInt`, `getLong`, `getBoolean`, `getMap`, `getList`) as well as the raw `bins` map and `getValue(String)`:

```java
// Typed getter (preferred):

String name = record.getString("name");

int age     = record.getInt("age");

// Generic:

Object raw = record.getValue("profile");    // same as record.bins.get("profile")

Object raw2 = record.bins.get("profile");   // also fine
```

There is no `record.get("binName")` method. Use `record.getValue("binName")` or `record.bins.get("binName")` for untyped access.

#### `record.getMap()` returns `AerospikeMap<?,?>`, not `Map<String, Object>`

`record.getMap("binName")` returns `AerospikeMap<?, ?>`. Because of Java’s wildcard bounds, this cannot be directly assigned to `Map<String, Object>` without a cast, even though `AerospikeMap` does implement `Map`. The two simplest approaches:

```java
// Option 1: using the bins field (cleanest, no annotation needed):

// record.bins is Map<String,Object>, so .get() returns Object

Map<?, ?> profile = (Map<?, ?>) record.bins.get("profile");

String level = (String) profile.get("level");

// Option 2: using getValue(), with unchecked cast to typed Map:

@SuppressWarnings("unchecked")

Map<String, Object> profile2 = (Map<String, Object>) record.getValue("profile");

String level2 = (String) profile2.get("level");
```

#### `Record` import disambiguation: don’t use wildcard imports

Don’t use `import com.aerospike.client.sdk.*;`. It causes a compile error in Java 16+ because both `com.aerospike.client.sdk.Record` and `java.lang.Record` are pulled into scope and the compiler cannot resolve the ambiguity. Always import every class explicitly:

```java
// Import com.aerospike.client.sdk.Record explicitly to avoid java.lang.Record conflict (see shared imports above).

// Do not use import com.aerospike.client.sdk.*;
```

### Mutable captures in lambdas

Java lambdas require all captured local variables to be effectively final. This applies to every mutable type: booleans, integer counters, long accumulators, and any other variable modified inside the lambda. Use the matching `Atomic*` wrapper:

```java
AtomicBoolean found       = new AtomicBoolean(false);

AtomicInteger chunkNumber = new AtomicInteger(1);

AtomicLong    recordCount = new AtomicLong(0L);

stream.forEach(result -> {

    if (result.isOk()) {

        found.set(true);

        chunkNumber.getAndIncrement();

        recordCount.incrementAndGet();

    }

});

if (found.get()) { System.out.println("Record found!"); }
```

### Accessing the 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)). Read it from there rather than from the bin-payload `Record`:

```python
async for row in stream:

    k = row.key

    # String key:

    str_key = k.value                 # returns a str if written with a string key

    # Integer key (no type coercion needed — Python is dynamic):

    int_key = k.value                 # returns an int if written with an integer key

    record = row.record_or_raise()

    # use record.bins["name"], record.bins["age"], etc.

stream.close()
```

::: row.key.value may be none in query results
`row.key.value` is only non-`None` when the user key was stored with the record at write time. Records written by external tooling, older clients, or any write that did not enable `send_key=True` will have `row.key.value is None`. Guard before using it:

```python
async for row in stream:

    key = row.key.value

    if key is not None and key.startswith("prefix-"):

        record = row.record_or_raise()

        # process record ...

stream.close()
```
:::

### Accessing bins on a `Record`

`record.bins` is a plain `dict`. Two access patterns:

```python
# Subscript (preferred when the bin is known-present; raises KeyError otherwise):

name = record.bins["name"]

age  = record.bins["age"]

# .get() for optional access (returns None if missing):

profile = record.bins.get("profile")
```

Bin values keep their Python types (`int`, `str`, `list`, `dict`, `bytes`, `bool`). No typed-getter methods and no `AerospikeMap`\-style wildcard-cast concerns — a `dict` bin is just a `dict`.

### Mutable captures in closures

Not applicable in Python. Regular closures capture the enclosing scope’s names, and mutation is fine:

```python
found = False

record_count = 0

async for row in stream:

    if row.is_ok:

        found = True

        record_count += 1

stream.close()

if found:

    print(f"Record found! ({record_count} total)")
```

No `Atomic*` wrappers needed — this is the standard Python iteration idiom.

## Query a range of partitions

You can limit a query to some of the namespace’s 4096 partitions. Splitting a set query by partition range lets several workers each read part of the set in parallel. Run the split against a quiet cluster: concurrent writes and migrations can make the counts differ, and parallel workers add read load on every node, so cap the number of workers in production.

`onPartitionRange(start, end)` in Java and `on_partition_range(start, end)` in Python read partitions from `start` (inclusive) to `end` (exclusive). `onPartition(id)` and `on_partition(id)` read a single partition. Partition IDs run from 0 to 4095. Both methods raise `IllegalArgumentException` (Java) or `ValueError` (Python) for a partition ID or range outside those bounds.

-   [Java](#tab-panel-5484)
-   [Python](#tab-panel-5485)

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

// Count the records a query returns.

ToIntFunction<RecordStream> countRecords = stream -> {

    int[] count = {0};

    stream.forEach(rr -> count[0]++);

    return count[0];

};

int firstHalf = countRecords.applyAsInt(session.query(orders).onPartitionRange(0, 2048).execute());

int secondHalf = countRecords.applyAsInt(session.query(orders).onPartitionRange(2048, 4096).execute());

int total = countRecords.applyAsInt(session.query(orders).execute());

// The two halves add up to the unrestricted total.

System.out.println(firstHalf + secondHalf == total);  // true
```

> 📖 **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.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) | [`ChainableQueryBuilder.onPartitionRange()`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/ChainableQueryBuilder.html#onPartitionRange%28int%2Cint%29) | [`ChainableQueryBuilder.onPartition()`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/ChainableQueryBuilder.html#onPartition%28int%29) | [`ChainableQueryBuilder.execute()`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/ChainableQueryBuilder.html#execute%28%29)

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

async def count_records(query):

    stream = await query.execute()

    count = 0

    async for _ in stream:

        count += 1

    stream.close()

    return count

first_half = await count_records(session.query(orders).on_partition_range(0, 2048))

second_half = await count_records(session.query(orders).on_partition_range(2048, 4096))

total = await count_records(session.query(orders))

# The two halves add up to the unrestricted total.

print(first_half + second_half == total)  # True
```

> 📖 **API reference**: [`DataSet.of()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/dataset.html#aerospike%5Fsdk.dataset.DataSet.of) | [`Session.query()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/session.html#aerospike%5Fsdk.aio.session.Session.query) | [`QueryBuilder.on_partition_range()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/query.html#aerospike%5Fsdk.aio.operations.query.QueryBuilder.on_partition%5Frange) | [`QueryBuilder.on_partition()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/query.html#aerospike%5Fsdk.aio.operations.query.QueryBuilder.on_partition) | [`QueryBuilder.execute()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/query.html#aerospike%5Fsdk.aio.operations.query.QueryBuilder.execute) | [`RecordStream.close()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/record-stream.html#aerospike%5Fsdk.record%5Fstream.RecordStream.close)

## Query without a filter

Query all records in a set:

-   [Java](#tab-panel-5486)
-   [Python](#tab-panel-5487)

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

// Get all users (use with caution on large datasets!)

RecordStream allStream = session.query(users).execute();

List<Record> allUsers = new ArrayList<>();

allStream.forEach(result -> {

    if (result.isOk()) {

        allUsers.add(result.recordOrThrow());

    }

});

// forEach closes allStream.

// Better: stream one record at a time without building a full list

RecordStream stream = session.query(users).execute();

stream.forEach(result -> {

    if (result.isOk()) {

        Record user = result.recordOrThrow();

        System.out.println(user.getString("name"));

    }

});
```

> 📖 **API reference**: [`Session.query(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/Session.html#query%28com.aerospike.client.sdk.DataSet%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.isOk()`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/RecordResult.html#isOk%28%29) | [`RecordResult.recordOrThrow()`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/RecordResult.html#recordOrThrow%28%29) | [`Record.getString(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/Record.html#getString%28java.lang.String%29)

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

# Get all users (use with caution on large datasets!)

all_stream = await session.query(users).execute()

all_users = []

async for row in all_stream:

    if row.is_ok:

        all_users.append(row.record_or_raise())

all_stream.close()

# Better: stream one record at a time without building a full list

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

async for row in stream:

    record = row.record_or_raise()

    print(record.bins.get("name"))

stream.close()
```

> 📖 **API reference**: [`DataSet.of()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/dataset.html#aerospike%5Fsdk.dataset.DataSet.of) | [`Session.query()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/session.html#aerospike%5Fsdk.aio.session.Session.query) | [`QueryBuilder.execute()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/query.html#aerospike%5Fsdk.aio.operations.query.QueryBuilder.execute) | [`RecordResult.is_ok`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/record-result.html#aerospike%5Fsdk.record%5Fresult.RecordResult.is%5Fok) | [`RecordResult.record_or_raise()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/record-result.html#aerospike%5Fsdk.record%5Fresult.RecordResult.record%5For%5Fraise) | [`RecordStream.close()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/record-stream.html#aerospike%5Fsdk.record%5Fstream.RecordStream.close)

::: reading a whole set
A query with no `where` clause reads every record in the set. Use it with care on large data sets, and consider a limit or streaming the results.
:::

## Complete example

This example is self-contained. It lists every import needed to run standalone. The seed data below uses a fixed list of keys; to seed a variable number of records instead, see [Dynamic batch building](https://aerospike.com/docs/develop/client/sdk/usage/batch#dynamic-batch-building).

-   [Java](#tab-panel-5488)
-   [Python](#tab-panel-5489)

```java
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 QueryRecordsExample {

    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 k1 = "query-example-1";

            String k2 = "query-example-2";

            String k3 = "query-example-3";

            String k4 = "query-example-4";

            // Cleanup so the example is repeatable.

            session.delete(users.ids(k1, k2, k3, k4)).execute().close();

            // Create sample data

            session.insert(users)

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

                .id(k1).values("Alice", 28, "active")

                .id(k2).values("Bob", 35, "active")

                .id(k3).values("Carol", 22, "inactive")

                .id(k4).values("David", 45, "active")

                .execute();

            // Simple query

            System.out.println("Active users:");

            RecordStream q1 = session.query(users)

                .where("$.status == 'active'")

                .execute();

            q1.forEach((RecordResult result) -> {

                Record u = result.recordOrThrow();

                System.out.println("  - " + u.getString("name"));

            });

            // Complex query

            System.out.println("\nActive adults over 30:");

            RecordStream q2 = session.query(users)

                .where("$.status == 'active' and $.age > 30")

                .readingOnlyBins("name", "age")

                .execute();

            q2.forEach(result -> {

                if (result.isOk()) {

                    Record u = result.recordOrThrow();

                    System.out.println(

                        "  - " + u.getString("name") + " (" + u.getInt("age") + ")"

                    );

                }

            });

            // Count

            RecordStream q3 = session.query(users)

                .where("$.status == 'active'")

                .execute();

            long activeCount = 0;

            while (q3.hasNext()) {

                RecordResult rr = q3.next();

                activeCount++;

            }

            q3.close();

            System.out.println("\nActive user count: " + activeCount);

        }

    }

}
```

> 📖 **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) | [`DataSet.ids(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/DataSet.html#ids%28java.lang.String...%29) | [`Session.delete(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/Session.html#delete%28java.util.List%29) | [`ChainableNoBinsBuilder.execute()`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/ChainableNoBinsBuilder.html#execute%28%29) | [`RecordStream.close()`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/RecordStream.html#close%28%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.id(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/IdValuesRowBuilder.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) | [`IdValuesRowBuilder.execute()`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/IdValuesRowBuilder.html#execute%28%29) | [`Session.query(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/Session.html#query%28com.aerospike.client.sdk.DataSet%29) | [`ChainableQueryBuilder.where(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/ChainableQueryBuilder.html#where%28java.lang.String%2Cjava.lang.Object...%29) | [`ChainableQueryBuilder.readingOnlyBins(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/ChainableQueryBuilder.html#readingOnlyBins%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) | [`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.isOk()`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/RecordResult.html#isOk%28%29) | [`RecordResult.recordOrThrow()`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/RecordResult.html#recordOrThrow%28%29) | [`Record.getString(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/Record.html#getString%28java.lang.String%29) | [`Record.getInt(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/Record.html#getInt%28java.lang.String%29) | [`RecordStream.hasNext()`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/RecordStream.html#hasNext%28%29) | [`RecordStream.next()`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/RecordStream.html#next%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")

        k1 = "query-example-1"

        k2 = "query-example-2"

        k3 = "query-example-3"

        k4 = "query-example-4"

        # Cleanup so the example is repeatable.

        await session.delete(users.ids(k1, k2, k3, k4)).execute()

        # Create sample data

        await (

            session.insert(users)

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

            .row(k1, "Alice", 28, "active")

            .row(k2, "Bob", 35, "active")

            .row(k3, "Carol", 22, "inactive")

            .row(k4, "David", 45, "active")

            .execute()

        )

        # Simple query

        print("Active users:")

        q1 = await session.query(users).where("$.status == 'active'").execute()

        async for row in q1:

            record = row.record_or_raise()

            print(f"  - {record.bins['name']}")

        q1.close()

        # Complex query

        print("\nActive adults over 30:")

        q2 = await (

            session.query(users)

            .where("$.status == 'active' and $.age > 30")

            .bins(["name", "age"])

            .execute()

        )

        async for row in q2:

            r = row.record_or_raise()

            print(f"  - {r.bins['name']} ({r.bins['age']})")

        q2.close()

        # Count

        q3 = await session.query(users).where("$.status == 'active'").execute()

        active_count = 0

        async for row in q3:

            row.record_or_raise()

            active_count += 1

        q3.close()

        print(f"\nActive user count: {active_count}")

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.ids()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/dataset.html#aerospike%5Fsdk.dataset.DataSet.ids) | [`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) | [`QueryBuilder.where()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/query.html#aerospike%5Fsdk.aio.operations.query.QueryBuilder.where) | [`QueryBuilder.bins()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/query.html#aerospike%5Fsdk.aio.operations.query.QueryBuilder.bins) | [`Session.delete()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/session.html#aerospike%5Fsdk.aio.session.Session.delete) | [`Session.insert()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/session.html#aerospike%5Fsdk.aio.session.Session.insert) | [`RecordResult.record_or_raise()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/record-result.html#aerospike%5Fsdk.record%5Fresult.RecordResult.record%5For%5Fraise) | [`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) | [`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)

## AEL and secondary indexes

AEL text does not force a primary index (PI) query. The optimizer can use available secondary indexes for selective predicates and fall back to a PI query when no useful index exists.

Both SDKs allow this fallback by default. To reject a `where()` query that no secondary index can serve, configure the query scope on the session’s behavior. In Java, derive a `Behavior` and call `allowScansWithWhere(false)` in an `.on(Selectors.reads().query(), ops -> ops.allowScansWithWhere(false))` patch. For one query only, use `.withHint(hint -> hint.disallowScansWithWhere())` instead (`QueryHint.Start.disallowScansWithWhere()`). In Python, pass [`Settings(allow_scans_with_where=False)`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/behavior.html#aerospike%5Fsdk.policy.behavior%5Fsettings.Settings.allow%5Fscans%5Fwith%5Fwhere) as `reads_query` to [`derive_with_changes`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/behavior.html#aerospike%5Fsdk.policy.behavior.Behavior.derive%5Fwith%5Fchanges). The query then fails with an index-not-found error (result code 201) instead of reading the whole set.

> 📖 **Learn more**: [AEL reference](https://aerospike.com/docs/develop/client/sdk/concepts/ael/reference) covers the full AEL syntax. [Primary index fallback](https://aerospike.com/docs/develop/learn/queries/query-optimizer/#control-pi-fallback) shows full behavior and per-query examples.

## API reference summary

| Method | Description |
| --- | --- |
| `session.query(dataSet)` | Start a query on a DataSet |
| `.where("expression")` | Filter with AEL expression (use `$.bin` for bin paths) |
| `.readingOnlyBins(bins...)` (Java) · `.bins([...])` (Python) | Select specific bins to return |
| `.limit(n)` | Limit number of results |
| `.chunkSize(n)` (Java) · `.chunk_size(n)` (Python) | Records fetched per round trip; drive with `stream.hasMoreChunks()` / `await stream.has_more_chunks()` |
| `.recordsPerSecond(n)` (Java) · `.records_per_second(n)` (Python) | Throttle the query to `n` records/sec per server node (`0` = unthrottled) |
| `.execute()` | Run the query and return a `RecordStream` |
| `RecordStream.forEach(...)` (Java) · `async for row in stream` (Python) | Iterate results — both auto-consume the stream on exhaustion; wrap in `try/finally` with `stream.close()` if you may abandon iteration early |

## Next steps

AEL Reference

Full AEL syntax and operators.

[AEL Reference →](https://aerospike.com/docs/develop/client/sdk/concepts/ael/reference)

Batch Operations

Efficient multi-record operations.

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

Async Operations

Non-blocking queries for high throughput.

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