Hyper-Converged Database (HCD) quickstart for tables (Python)

network_check Beginner
query_builder 15 min

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 with vector embeddings to a table, and perform a vector search to find similar data.

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

Store your endpoint

The Data API endpoint for your database has the form: http://CLUSTER_HOST:GATEWAY_PORT

  • Replace CLUSTER_HOST with the external IP address of any node in your cluster. To find this, run kubectl get nodes -o wide and use any of the values listed under "EXTERNAL-IP" in the output.

  • Replace GATEWAY_PORT with the port number for your API gateway service. To find this, run kubectl get svc and look for the "PORT(S)" value that corresponds to NodePort.

For this quickstart, store the endpoint in an environment variable:

  • Linux or macOS

  • Windows

export API_ENDPOINT=API_ENDPOINT
set API_ENDPOINT=API_ENDPOINT

Store your username and password

You set a username and password when you create a cluster.

If you didn’t provide superuser credentials when you created your cluster, they were generated automatically and saved in a superuser secret named CLUSTER_NAME-superuser. The CLUSTER_NAME-superuser secret contains both the username and the password.

For this quickstart, store the username and password in environment variables:

  • Linux or macOS

  • Windows

export USERNAME=USERNAME
export PASSWORD=PASSWORD
set USERNAME=USERNAME
set PASSWORD=PASSWORD

Install a client

Install one of the 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.10 to 3.14 or later if needed.

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

  3. Install the latest version of the astrapy package.

    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.py
import os

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


def connect_to_database() -> Database:
    """
    Connects to your database.
    This function retrieves the database endpoint, username, and password from the
    environment variables `API_ENDPOINT`, `USERNAME`, and `PASSWORD`.

    Returns:
        Database: An instance of the connected database.

    Raises:
        RuntimeError: If the environment variables `API_ENDPOINT`,
        `USERNAME`, or `PASSWORD` are not defined.
    """
    endpoint = os.environ.get("API_ENDPOINT")  (1)
    username = os.environ.get("USERNAME")
    password = os.environ.get("PASSWORD")

    if not endpoint or not username or not password:
        raise RuntimeError(
            "Environment variables API_ENDPOINT, USERNAME, and PASSWORD must be defined"
        )

    # Create an instance of the `DataAPIClient` class
    client = DataAPIClient(environment=Environment.HCD)

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

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

    return database
1 Store your database’s endpoint, username, and password in environment variables named API_ENDPOINT, USERNAME, and PASSWORD, as instructed in Store your endpoint and Store your username and password.

Create a keyspace

The following code will create a new keyspace in your database.

  1. Copy the code into your project.

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

  3. Execute the code.

    For information about executing code, refer to the documentation for your programming language.

    Once the code completes, you should see a printed message confirming keyspace creation.

quickstart_create_keyspace.py
from quickstart_connect import connect_to_database  (1)


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

    # Get an admin object
    admin = database.get_database_admin()

    # Create a keyspace
    admin.create_keyspace("quickstart_keyspace")  (2)

    print(f"Created keyspace")


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, username, and password in environment variables as instructed in Store your endpoint and Store your username and password.

2 This code creates a keyspace named quickstart_keyspace. If you want to use a different name, change the name before running the code.

Create a table

The following code 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 code will index some columns so that you can find and sort data in those columns.

  1. Copy the code into your project.

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

  3. Execute the code.

    For information about executing code, refer to the documentation for your programming language.

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

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


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. (2)
        .add_vector_column("summary_genres_vector", dimension=5)
        # 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)
        keyspace="quickstart_keyspace",  (4)
        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,  (5)
        ),
    )

    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, username, and password in environment variables as instructed in Store your endpoint and Store your username and password.

2 This column will store 5-dimensional vector data.
3 This code creates a table named quickstart_table. If you want to use a different name, change the name before running the code.
4 This code expects that you have a keyspace named quickstart_keyspace. If you used a different keyspace name in the previous section, update it here.
5 This vector column will use the cosine similarity metric to compare vectors.

Insert data to your table

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

  1. Copy the code 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 code 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 code.

    For information about executing code, refer to the documentation for your programming language.

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

quickstart_insert_to_table.py
import json

from astrapy.data_types import DataAPIDate, DataAPIVector
from quickstart_connect import connect_to_database  (1)


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

    table = database.get_table(
        "quickstart_table", keyspace="quickstart_keyspace"
    )  (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": DataAPIVector(
                data["summary_genres_vector"]
            ),
        }
        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, username, and password in environment variables as instructed in Store your endpoint and Store your username and password.

2 This code expects that you have a table named quickstart_table in a keyspace named quickstart_keyspace. If you used a different keyspace or table name in the previous sections, update it here.
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 vector.

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

quickstart_find_rows.py
from astrapy.data_types import DataAPIVector
from quickstart_connect import connect_to_database  (1)


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

    table = database.get_table(
        "quickstart_table", keyspace="quickstart_keyspace"
    )  (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 vector
    print("\nUsing vector search to find a book...")

    single_vector_match = table.find_one(
        {},
        sort={
            "summary_genres_vector": DataAPIVector(
                [
                    0.016326904,
                    -0.031677246,
                    0.04815674,
                    0.0033435822,
                    0.01876831,
                ]
            )
        },
        projection={"title": True},
    )

    print(f"{single_vector_match['title']} is the best match")

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

    vector_cursor = table.find(
        {"number_of_pages": {"$gt": 400}},
        sort={
            "summary_genres_vector": DataAPIVector(
                [
                    0.016326904,
                    -0.031677246,
                    0.04815674,
                    0.0033435822,
                    0.01876831,
                ]
            )
        },
        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 This code expects that you have a table named quickstart_table in a keyspace named quickstart_keyspace. If you used a different keyspace or table name in the previous sections, update it here.

Next steps

For more practice, you can continue building with the table 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.

Insert 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.

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 Find rows (Python), Filter operators for tables (Python), Sort clauses for tables (Python), and Find data with vector search.

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