Find rows (Python)

Finds rows in a table using filter and sort clauses, including vector search.

For general information about working with tables and rows, see About tables with the Data API (Python).

Ready to write code? See the examples for this method to get started. If you are new to the Data API, check out the quickstart.

Result

Returns a cursor (astrapy.cursors.TableFindCursor) for iterating over rows that match the specified filter and sort clauses.

The columns included in the returned rows depend on the subset of columns that were requested in the projection.

If requested and applicable, each row will also include a $similarity key with a numeric similarity score that represents the closeness of the sort vector and the row’s vector.

You must iterate over the cursor to fetch matching rows. For details about iteration, see Iterate over found rows.

When you iterate over the cursor, rows are fetched in batches. The fetched batches may reflect real-time updates on the table.

For more information about iterating over and manipulating the cursor, see FindCursor.

Parameters

Use the find method, which belongs to the astrapy.Table class.

Method signature
find(
  filter: Dict[str, Any],
  *,
  projection: Iterable[str] | Dict[str, bool],
  row_type: type,
  skip: int,
  limit: int,
  include_similarity: bool,
  sort: Dict[str, Any],
  initial_page_state: str,
  request_timeout_ms: int,
  timeout_ms: int,
) -> TableFindCursor

For best performance, filter and sort on indexed columns, partition keys, and clustering keys.

Filtering on non-indexed columns is inefficient and resource-intensive, especially for large datasets. With the Data API clients, such operations can hit the client timeout limit before the underlying HTTP operation is complete. If you filter on non-indexed columns, the Data API will give a warning.

An empty filter or omitted filter may also result in an inefficient and long-running operation.

Additionally, the Data API can perform in-memory sorting, depending on the columns you sort on, the table’s partitioning structure, and whether the sorted columns are indexed. In-memory sorts can have performance implications.

Name Type Summary

filter

Dict[str, Any]

Optional. An object that defines filter criteria using the Data API filter syntax. The method only finds rows that match the filter criteria. Filters can improve performance by reducing the number of rows that the Data API processes.

For a list of available filter operators and more examples, see Filter operators for tables (Python).

To perform a vector search, use sort instead of filter.

To avoid fetching unnecessary rows, which can contain tombstones, DataStax recommends that you use a filter that limits the number of rows scanned. For example, filter on partition key columns or indexed columns.

Default: No filter

For an example, see Use filters to find rows.

sort

Dict[str, Any]

Optional. Sorts rows by one or more columns, or performs a vector search.

For more information, see Sort clauses for tables (Python).

projection

Dict[str, bool]

Optional. Controls which columns are included or excluded in the returned rows.

For more information, see Projections for tables (Python).

DataStax recommends a projection to avoid unnecessarily returning large columns, such as vector columns with highly dimensional embeddings.

Default: All columns

row_type

type

Optional. A formal specifier for the type checker.

This parameter is useful if your code is strictly typed and you use a projection.

For more information, see Typing support.

Default: The same type as the rows in the table. If you didn’t specify this when you instantiated the Table object, the row type defaulted to dict.

skip

int

Optional. The number of rows to bypass (skip) before returning rows.

The API excludes the first n rows matching the query, and the results begin at the n+1 row.

This parameter only applies if you also explicitly specify an ascending or descending sort criterion. This parameter is not valid with vector search.

limit

int

Optional. Limit the total number of rows returned. Once limit is reached, or the cursor is exhausted due to lack of matching rows, nothing more is returned.

For vector search, a lower limit reduces the accuracy of the search and the time required for the search.

include_similarity

bool

Optional. Whether to include a $similarity property in the response. The $similarity value represents the closeness of the sort vector and the row’s vector.

Default: false

initial_page_state

str

Optional. The next_page_state value from the response of fetch_next_page() called on a previous cursor. You cannot pass None, which is the value of next_page_state when no pages remain.

Used to manually request the next page of results. This is useful for cases where an external action triggers fetching the next page of results.

For usage, see Iterate over found rows.

request_timeout_ms

int

Optional. The maximum time, in milliseconds, that the client should wait for the underlying HTTP request.

This parameter is aliased as request_timeout_ms and timeout_ms for convenience.

Default: The default value for the table. This default is 30 seconds unless you specified a different default when you initialized the Table or DataAPIClient object. For more information, see Timeout options.

Examples

The following examples demonstrate how to find rows in a table.

Use filters to find rows

You can use a filter to find rows that match specific criteria. For example, you can find rows with an is_checked_out value of false and a number_of_pages value less than 300.

For optimal performance, you only filter on indexed columns. The Data API returns a warning if you filter on a non-indexed column.

For a list of available filter operators, see Filter operators for tables (Python).

The following example uses untyped documents or rows, but you can define a client-side type for your collection to help statically catch errors. For examples, see Typing support.

from astrapy import DataAPIClient
from astrapy.authentication import UsernamePasswordTokenProvider
from astrapy.constants import Environment

# Get an existing table
client = DataAPIClient(environment=Environment.HCD)
database = client.get_database(
    "API_ENDPOINT",
    token=UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
    keyspace="KEYSPACE_NAME",
)
table = database.get_table("TABLE_NAME")

# Find rows
cursor = table.find(
    {
        "$and": [
            {"is_checked_out": False},
            {"number_of_pages": {"$lt": 300}},
        ]
    }
)

# Iterate over the found rows
for row in cursor:
    print(row)

Use vector search with a search vector to find rows

Perform a vector search by providing a search vector in the sort clause. This returns the row whose vector column value is most similar to the provided search vector.

The vector column must be indexed.

If your table has multiple vector columns, you can only sort on one vector column at a time.

You can use the astrapy.data_types.DataAPIVector class to binary-encode your search vector. DataStax recommends that you always use a DataAPIVector object instead of a list of floats to improve performance.

When you read the value of a vector column, the client always returns a DataAPIVector object, unless you change the default serialization/deserialization behavior.

from astrapy import DataAPIClient
from astrapy.authentication import UsernamePasswordTokenProvider
from astrapy.constants import Environment
from astrapy.data_types import DataAPIVector

# Get an existing table
client = DataAPIClient(environment=Environment.HCD)
database = client.get_database(
    "API_ENDPOINT",
    token=UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
    keyspace="KEYSPACE_NAME",
)
table = database.get_table("TABLE_NAME")

# Find rows
cursor = table.find(
    {}, sort={"summary_genres_vector": DataAPIVector([0.08, -0.62, 0.39])}
)

# Iterate over the found rows
for row in cursor:
    print(row)

Use lexicographical matching to find rows

Lexicographical matching is currently in public preview. Development is ongoing, and the features and functionality are subject to change. Hyper-Converged Database (HCD), and the use of such, is subject to the DataStax Preview Terms.

There are two ways to use lexicographical matching to find rows with the Data API:

  • Sort to find rows with a text or ascii column value that is most relevant to a given string of space-separated keywords or terms.

  • Filter with the $match operator to find rows with a text or ascii column value that is a lexicographical match to the specified string of space-separated keywords or terms

You can use these strategies together or separately.

Lexicographical matching is only available for text or ascii columns that have a text index, not a regular index. For more information, see Create a text index (Python) and Indexes in tables (Python).

The following example uses untyped documents or rows, but you can define a client-side type for your collection to help statically catch errors. For examples, see Typing support.

from astrapy import DataAPIClient
from astrapy.authentication import UsernamePasswordTokenProvider
from astrapy.constants import Environment

# Get an existing table
client = DataAPIClient(environment=Environment.HCD)
database = client.get_database(
    "API_ENDPOINT",
    token=UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
    keyspace="KEYSPACE_NAME",
)
table = database.get_table("TABLE_NAME")

# Find rows
cursor = table.find(
    {"summary": {"$match": "futuristic laboratory discovery"}},
    sort={"summary": "futuristic laboratory"},
)

# Iterate over the found rows
for row in cursor:
    print(row)

Use sorting to find rows

You can use a sort clause to sort rows by one or more columns.

For best performance, only sort on columns that are indexed or that are part of the primary key.

For more information, see Sort clauses for tables (Python).

The following example uses untyped documents or rows, but you can define a client-side type for your collection to help statically catch errors. For examples, see Typing support.

from astrapy import DataAPIClient
from astrapy.authentication import UsernamePasswordTokenProvider
from astrapy.constants import Environment, SortMode

# Get an existing table
client = DataAPIClient(environment=Environment.HCD)
database = client.get_database(
    "API_ENDPOINT",
    token=UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
    keyspace="KEYSPACE_NAME",
)
table = database.get_table("TABLE_NAME")

# Find rows
cursor = table.find(
    {"is_checked_out": False},
    sort={
        "rating": SortMode.ASCENDING,
        "title": SortMode.DESCENDING,
    },
)

# Iterate over the found rows
for row in cursor:
    print(row)

Use an empty filter to find all rows

To find all rows, use an empty filter.

Avoid this if you have a large number of rows.

The following example uses untyped documents or rows, but you can define a client-side type for your collection to help statically catch errors. For examples, see Typing support.

from astrapy import DataAPIClient
from astrapy.authentication import UsernamePasswordTokenProvider
from astrapy.constants import Environment

# Get an existing table
client = DataAPIClient(environment=Environment.HCD)
database = client.get_database(
    "API_ENDPOINT",
    token=UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
    keyspace="KEYSPACE_NAME",
)
table = database.get_table("TABLE_NAME")

# Find rows
cursor = table.find({})

# Iterate over the found rows
for row in cursor:
    print(row)

Include the similarity score with the result

If you use a vector search to find rows, you can also include a $similarity property in the result. The $similarity value represents the closeness of the sort vector and the value of the row’s vector column.

This parameter doesn’t work with vectorize; it only works if you provide the search vector for vector search directly.

The client always returns the similarity score as a DataAPIVector object, unless you change the default serialization/deserialization behavior.

from astrapy import DataAPIClient
from astrapy.authentication import UsernamePasswordTokenProvider
from astrapy.constants import Environment
from astrapy.data_types import DataAPIVector

# Get an existing table
client = DataAPIClient(environment=Environment.HCD)
database = client.get_database(
    "API_ENDPOINT",
    token=UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
    keyspace="KEYSPACE_NAME",
)
table = database.get_table("TABLE_NAME")

# Find rows
cursor = table.find(
    {},
    sort={"summary_genres_vector": DataAPIVector([0.08, -0.62, 0.39])},
    include_similarity=True,
)

# Iterate over the found rows
for row in cursor:
    print(row["$similarity"])

Include only specific columns in the response

To specify which columns to include or exclude in the returned row, use a projection.

The following example demonstrates an inclusive projection.

The following example uses untyped documents or rows, but you can define a client-side type for your collection to help statically catch errors. For examples, see Typing support.

from astrapy import DataAPIClient
from astrapy.authentication import UsernamePasswordTokenProvider
from astrapy.constants import Environment

# Get an existing table
client = DataAPIClient(environment=Environment.HCD)
database = client.get_database(
    "API_ENDPOINT",
    token=UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
    keyspace="KEYSPACE_NAME",
)
table = database.get_table("TABLE_NAME")

# Find rows
cursor = table.find(
    {"number_of_pages": {"$lt": 300}},
    projection={"is_checked_out": True, "title": True},
)

# Iterate over the found rows
for row in cursor:
    print(row)

Exclude specific columns from the response

To specify which columns to include or exclude in the returned row, use a projection.

The following example demonstrates an exclusive projection.

The following example uses untyped documents or rows, but you can define a client-side type for your collection to help statically catch errors. For examples, see Typing support.

from astrapy import DataAPIClient
from astrapy.authentication import UsernamePasswordTokenProvider
from astrapy.constants import Environment

# Get an existing table
client = DataAPIClient(environment=Environment.HCD)
database = client.get_database(
    "API_ENDPOINT",
    token=UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
    keyspace="KEYSPACE_NAME",
)
table = database.get_table("TABLE_NAME")

# Find rows
cursor = table.find(
    {"number_of_pages": {"$lt": 300}},
    projection={"is_checked_out": False, "title": False},
)

# Iterate over the found rows
for row in cursor:
    print(row)

Limit the number of rows returned

Specify a limit to only fetch up to a certain number of rows.

The following example uses untyped documents or rows, but you can define a client-side type for your collection to help statically catch errors. For examples, see Typing support.

from astrapy import DataAPIClient
from astrapy.authentication import UsernamePasswordTokenProvider
from astrapy.constants import Environment

# Get an existing table
client = DataAPIClient(environment=Environment.HCD)
database = client.get_database(
    "API_ENDPOINT",
    token=UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
    keyspace="KEYSPACE_NAME",
)
table = database.get_table("TABLE_NAME")

# Find rows
cursor = table.find(
    {
        "$and": [
            {"is_checked_out": False},
            {"number_of_pages": {"$lt": 300}},
        ]
    },
    limit=3,
)

# Iterate over the found rows
for row in cursor:
    print(row)

Skip rows

You can specify a number of rows to skip (bypass) before returning rows.

You can only do this if your find explicitly includes an ascending or descending sort criterion. You cannot do this in conjunction with vector search.

The following example uses untyped documents or rows, but you can define a client-side type for your collection to help statically catch errors. For examples, see Typing support.

from astrapy import DataAPIClient
from astrapy.authentication import UsernamePasswordTokenProvider
from astrapy.constants import Environment, SortMode

# Get an existing table
client = DataAPIClient(environment=Environment.HCD)
database = client.get_database(
    "API_ENDPOINT",
    token=UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
    keyspace="KEYSPACE_NAME",
)
table = database.get_table("TABLE_NAME")

# Find rows
cursor = table.find(
    {"is_checked_out": False},
    sort={
        "rating": SortMode.ASCENDING,
        "title": SortMode.DESCENDING,
    },
    skip=5,
)

# Iterate over the found rows
for row in cursor:
    print(row)

Use filter, sort, and projection together

The following example uses untyped documents or rows, but you can define a client-side type for your collection to help statically catch errors. For examples, see Typing support.

from astrapy import DataAPIClient
from astrapy.authentication import UsernamePasswordTokenProvider
from astrapy.constants import Environment, SortMode

# Get an existing table
client = DataAPIClient(environment=Environment.HCD)
database = client.get_database(
    "API_ENDPOINT",
    token=UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
    keyspace="KEYSPACE_NAME",
)
table = database.get_table("TABLE_NAME")

# Find rows
cursor = table.find(
    {
        "$and": [
            {"is_checked_out": False},
            {"number_of_pages": {"$lt": 300}},
        ]
    },
    sort={
        "rating": SortMode.ASCENDING,
        "title": SortMode.DESCENDING,
    },
    projection={"is_checked_out": True, "title": True},
)

# Iterate over the found rows
for row in cursor:
    print(row)

Iterate over found rows

Use a for loop to iterate over the cursor. The client will periodically fetch more rows until no matching rows remain.

Alternatively, you can use the initial_page_state parameter to fetch a specific page of results. This is useful for cases where an external action triggers fetching the next page of results. For example, you might use this feature if you implement an infinite scroll interface or a button to load more results.

If you need a list of all results, call to_list(). However, the time and memory required for this operation depend on the number of results. This is not recommended when you expect a large number of roes.

Example using for:

from astrapy import DataAPIClient
from astrapy.authentication import UsernamePasswordTokenProvider
from astrapy.constants import Environment

# Get an existing table
client = DataAPIClient(environment=Environment.HCD)
database = client.get_database(
    "API_ENDPOINT",
    token=UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
    keyspace="KEYSPACE_NAME",
)
table = database.get_table("TABLE_NAME")

# Find rows
cursor = table.find(
    {
        "$and": [
            {"is_checked_out": False},
            {"number_of_pages": {"$lt": 300}},
        ]
    }
)

# Iterate over the found rows
for row in cursor:
    print(row)

Example using initial_page_state:

from astrapy import DataAPIClient
from astrapy.authentication import UsernamePasswordTokenProvider
from astrapy.constants import Environment

# Get an existing table
client = DataAPIClient(environment=Environment.HCD)
database = client.get_database(
    "API_ENDPOINT",
    token=UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
    keyspace="KEYSPACE_NAME",
)
table = database.get_table("TABLE_NAME")

# Create the filter
filter = {
    "$and": [
        {"is_checked_out": False},
        {"number_of_pages": {"$lt": 300}},
    ]
}

# Get the first page
cursor_1 = table.find(filter)
page_1 = cursor_1.fetch_next_page()
results_1 = page_1.results
for row in results_1:
    print(row)
pagination_state_1 = page_1.next_page_state

# Get the next page
if pagination_state_1:
    cursor_2 = table.find(filter, initial_page_state=pagination_state_1)
    page_2 = cursor_2.fetch_next_page()
    results_2 = page_2.results
    for row in results_2:
        print(row)
    pagination_state_2 = page_2.next_page_state

Client reference

For more information, see the client reference.

Was this helpful?

Give Feedback

How can we improve the documentation?

© Copyright IBM Corporation 2026 | Privacy policy | Terms of use Manage Privacy Choices

Apache, Apache Cassandra, Cassandra, Apache Tomcat, Tomcat, Apache Lucene, Apache Solr, Apache Hadoop, Hadoop, Apache Pulsar, Pulsar, Apache Spark, Spark, Apache TinkerPop, TinkerPop, Apache Kafka and Kafka are either registered trademarks or trademarks of the Apache Software Foundation or its subsidiaries in Canada, the United States and/or other countries. Kubernetes is the registered trademark of the Linux Foundation.

General Inquiries: Contact IBM