Astra DB Serverless quickstart for tables

network_check Beginner
query_builder 15 min

Tables with the Data API are currently in public preview. Development is ongoing, and the features and functionality are subject to change. Astra DB Serverless, and the use of such, is subject to the DataStax Preview Terms.

If your data is not fully structured, or if you do not want to use a fixed schema, see the quickstart for collections instead.

This quickstart demonstrates how to create a table schema, insert data to a table, generate vector embeddings, and perform a vector search to find similar data.

The Next steps section discusses how to insert other types of data, use a different embedding model, insert data with pre-generated vector embeddings, or skip embedding generation.

To learn more about vector databases and vector search, see What are vector databases? and What is Vector Search.

Create a database and store your credentials

  1. Sign in or create an Astra account.

  2. In the Astra Portal navigation menu, click Databases, and then click Create Database.

  3. For this quickstart, select the following:

    • Serverless (Vector) as the deployment type

    • Amazon Web Services as the provider

    • us-east-2 as the region

  4. Click Create Database.

    Wait for your database to initialize and reach Active status. This can take several minutes.

  5. Under Database Details, copy your database’s API endpoint.

  6. Under Database Details, click Generate Token, then copy the token.

  7. For this quickstart, store the endpoint and token in environment variables:

    bash
    export API_ENDPOINT=API_ENDPOINT
    export APPLICATION_TOKEN=APPLICATION_TOKEN

Install a client

Install one of the Astra DB Data API clients to facilitate interactions with the Data API. To use the Data API with tables, you must install client version 2.0.x.

  1. Update to Python version 3.8 or later if needed.

  2. Update to pip version 23.0 or later if needed.

  3. Install the latest version of the astrapy package Latest astrapy release on GitHub.

    shell
    pip install "astrapy>=2.0,<3.0"

Connect to your database

The following function will connect to your database.

Copy the file into your project. You don’t need to execute the function now; the subsequent code examples will import and use this function.

quickstart_connect.pypython
import os
from astrapy import DataAPIClient, Database


def connect_to_database() -> Database:
    """
    Connects to a DataStax Astra database.
    This function retrieves the database endpoint and application token from the
    environment variables `API_ENDPOINT` and `APPLICATION_TOKEN`.

    Returns:
        Database: An instance of the connected database.

    Raises:
        RuntimeError: If the environment variables `API_ENDPOINT` or
        `APPLICATION_TOKEN` are not defined.
    """
    endpoint = os.environ.get("API_ENDPOINT")  (1)
    token = os.environ.get("APPLICATION_TOKEN")

    if not token or not endpoint:
        raise RuntimeError(
            "Environment variables API_ENDPOINT and APPLICATION_TOKEN must be defined"
        )

    # Create an instance of the `DataAPIClient` class
    client = DataAPIClient()

    # Get the database specified by your endpoint and provide the token
    database = client.get_database(endpoint, token=token)

    print(f"Connected to database {database.info().name}")

    return database
1 Store your database’s endpoint and application token in environment variables named API_ENDPOINT and APPLICATION_TOKEN, as instructed in Create a database and store your credentials.

Create a table

The following script will create an empty table in your database. The table created here matches the structure of the data that you will insert to the table. After creating the table, the script will index some columns so that you can find and sort data in those columns.

  1. Copy the script into your project.

  2. If needed, update the import path to the "connect to database" function from the previous section.

  3. Execute the script.

    For information about executing scripts, refer to the documentation for the language that your script uses.

    Once the script completes, you should see a printed message confirming the table creation.

quickstart_create_table.pypython
from quickstart_connect import connect_to_database  (1)
from astrapy.info import (
    CreateTableDefinition,
    ColumnType,
    TableVectorIndexOptions,
    VectorServiceOptions,
)
from astrapy.constants import VectorMetric


def main() -> None:
    database = connect_to_database()

    table_definition = (
        CreateTableDefinition.builder()
        # Define all of the columns in the table
        .add_column("title", ColumnType.TEXT)
        .add_column("author", ColumnType.TEXT)
        .add_column("number_of_pages", ColumnType.INT)
        .add_column("rating", ColumnType.FLOAT)
        .add_column("publication_year", ColumnType.INT)
        .add_column("summary", ColumnType.TEXT)
        .add_set_column(
            "genres",
            ColumnType.TEXT,
        )
        .add_map_column(
            "metadata",
            # This is the key type for the map column
            ColumnType.TEXT,
            # This is the value type for the map column
            ColumnType.TEXT,
        )
        .add_column("is_checked_out", ColumnType.BOOLEAN)
        .add_column("borrower", ColumnType.TEXT)
        .add_column("due_date", ColumnType.DATE)
        # This column will store vector embeddings.
        # The column will use an embedding model from NVIDIA to generate the
        # vector embeddings when data is inserted to the column. (2)
        .add_vector_column(
            "summary_genres_vector",
            dimension=1024,
            service=VectorServiceOptions(
                provider="nvidia",
                model_name="NV-Embed-QA",
            ),
        )
        # Define the primary key for the table.
        # In this case, the table uses a composite primary key.
        .add_partition_by(["title", "author"])
        # Finally, build the table definition.
        .build()
    )

    table = database.create_table(
        "quickstart_table",  (3)
        definition=table_definition,
    )

    print("Created table")

    # Index any columns that you want to sort and filter on.
    table.create_index(
        "rating_index",
        column="rating",
    )

    table.create_index(
        "number_of_pages_index",
        column="number_of_pages",
    )

    table.create_vector_index(
        "summary_genres_vector_index",
        column="summary_genres_vector",
        options=TableVectorIndexOptions(
            metric=VectorMetric.COSINE,
        ),
    )

    print("Indexed columns")


if __name__ == "__main__":
    main()
1 This is the connect_to_database function from the previous section. Update the import path if necessary.

To use the function, ensure you stored your database’s endpoint and application token in environment variables as instructed in Create a database and store your credentials.

2 This column will use the Astra-hosted NVIDIA embedding model to generate vector embeddings. This is currently only supported in certain regions. Ensure that your database is in the Amazon Web Services us-east-2 region, as instructed in Create a database and store your credentials.
3 This script creates a table named quickstart_table. If you want to use a different name, change the name before running the script.

Insert data to your table

The following script will insert data from a JSON file into a your table.

  1. Copy the script into your project.

  2. Download the quickstart_dataset.json sample dataset (76 kB). This dataset is a JSON array describing library books.

  3. Replace PATH_TO_DATA_FILE in the script with the path to the dataset.

  4. If needed, update the import path to the "connect to database" function from the previous section.

  5. Execute the script.

    For information about executing scripts, refer to the documentation for the language that your script uses.

    Once the script completes, you should see a printed message confirming the insertion of 100 rows.

quickstart_insert_to_table.pypython
from quickstart_connect import connect_to_database  (1)
from astrapy.data_types import DataAPIDate
import json


def main() -> None:
    database = connect_to_database()

    table = database.get_table("quickstart_table")  (2)

    data_file_path = "PATH_TO_DATA_FILE"  (3)

    with open(data_file_path, "r", encoding="utf8") as file:
        json_data = json.load(file)

    rows = [
        {
            **data,
            "due_date": (
                DataAPIDate.from_string(data["due_date"])
                if data.get("due_date")
                else None
            ),
            "summary_genres_vector": (
                f"summary: {data['summary']} | genres: {', '.join(data['genres'])}"
            ),
        }
        for data in json_data
    ]

    insert_result = table.insert_many(rows)

    print(f"Inserted {len(insert_result.inserted_ids)} rows")


if __name__ == "__main__":
    main()
1 This is the connect_to_database function from the previous section. Update the import path if necessary.

To use the function, ensure you stored your database’s endpoint and application token in environment variables as instructed in Create a database and store your credentials.

2 If you changed the table name in the previous script, change it in this script as well.
3 Replace PATH_TO_DATA_FILE with the path to the JSON data file.

Find data in your table

After you insert data to your table, you can search the data. In addition to traditional database filtering, you can perform a vector search to find data that is most similar to a search string.

The following script performs three searches on the sample data that you loaded in Insert data to your table.

quickstart_find_rows.pypython
from quickstart_connect import connect_to_database  (1)


def main() -> None:
    database = connect_to_database()

    table = database.get_table("quickstart_table")  (2)

    # Find rows that match a filter
    print("\nFinding books with rating greater than 4.7...")

    rating_cursor = table.find(
        {"rating": {"$gt": 4.7}},
        projection={"title": True, "rating": True}
    )

    for row in rating_cursor:
        print(f"{row['title']} is rated {row['rating']}")

    # Perform a vector search to find the closest match to a search string
    print("\nUsing vector search to find a single scary novel...")

    single_vector_match = table.find_one(
        {},
        sort={"summary_genres_vector": "A scary novel"},
        projection={"title": True}
    )

    print(f"{single_vector_match['title']} is a scary novel")

    # Combine a filter and vector search to find the 3 books with
    # more than 400 pages that are the closest matches to a search string
    print(
        "\nUsing filters and vector search to find 3 books with more than 400 pages that are set in the arctic, returning just the title and author..."
    )

    vector_cursor = table.find(
        {"number_of_pages": {"$gt": 400}},
        sort={"summary_genres_vector": "A book set in the arctic"},
        limit=3,
        projection={"title": True, "author": True},
    )

    for row in vector_cursor:
        print(row)


if __name__ == "__main__":
    main()
1 This is the connect_to_database function from the previous section. Update the import path if necessary.
2 If you changed the table name in the previous script, change it in this script as well.

Next steps

For more practice, you can continue building with the database that you created here. For example, try inserting more data to the table, or try different searches. The Data API reference provides code examples for various operations.

Upload data from different sources

This quickstart demonstrated how to insert structured data from a JSON file into a table, but you can insert data from many sources.

Tables use fixed schemas. If your data is unstructured or if you want a flexible schema, you can use a collection instead of a table. See the quickstart for collections.

Use a different method to generate vector embeddings

This quickstart used the Astra-hosted NVIDIA embedding model to generate vector embeddings. You can also use other embedding models, or you can insert data with pre-generated vector embeddings (or without vector embeddings) and skip embedding.

Perform more complex searches

This quickstart demonstrated how to find data using filters and vector search. To learn more about the searches you can perform, see About tables with the Data API and Find data with vector search.

Use different database settings

For this quickstart, you need a Serverless (Vector) database in the Amazon Web Services us-east-2 region, which is required for the Astra-hosted NVIDIA embedding model integration.

For production databases, you might use different database settings.

Was this helpful?

Give Feedback

How can we improve the documentation?

© 2025 DataStax | 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: +1 (650) 389-6000, info@datastax.com