Connect with the Python client
Learn how to connect to a DSE database with the AstraPy client.
Prerequisites
-
You have installed a cluster.
-
You have created a keyspace.
-
You have installed Python 3.8 or higher, and pip 23.0 or higher.
Install the Python client
Use pip to install the Python client.
To install the Python client with pip:
-
Verify that pip is version 23.0 or higher.
pip --version
-
Upgrade pip if needed.
python -m pip install --upgrade pip
-
Install the
astrapy
package. You must have Python 3.8 or higher.pip install astrapy
Connect to a vector-enabled DataStax Enterprise (DSE) database
Create a file named quickstart.py
with the following content:
import os
from astrapy import DataAPIClient
from astrapy.constants import Environment
from astrapy.authentication import UsernamePasswordTokenProvider
from astrapy.constants import VectorMetric
from astrapy.ids import UUID
from astrapy.exceptions import InsertManyException
from astrapy.info import CollectionVectorServiceOptions
# Database settings
DB_USERNAME = "cassandra"
DB_PASSWORD = "cassandra"
DB_API_ENDPOINT = "http://localhost:8181"
DB_NAMESPACE = "my_namespace"
DB_COLLECTION = "vector_test"
# Database settings if you exported them as environment variables
# DB_USERNAME = os.environ.get("DB_USERNAME")
# DB_PASSWORD = os.environ.get("DB_PASSWORD")
# DB_API_ENDPOINT = os.environ.get("DB_API_ENDPOINT")
# Embedding provider settings
EMBEDDING_PROVIDER = "openai";
EMBEDDING_MODEL_NAME = "text-embedding-3-small";
EMBEDDING_DIMENSIONS = 1024
EMBEDDING_API_KEY = os.environ.get("EMBEDDING_API_KEY");
# Build a token
tp = UsernamePasswordTokenProvider(DB_USERNAME, DB_PASSWORD)
# Initialize the client and get a "Database" object
client = DataAPIClient(environment=Environment.DSE)
database = client.get_database(DB_API_ENDPOINT, token=tp)
database.get_database_admin().create_namespace(DB_NAMESPACE, update_db_namespace=True)
Run the script with python quickstart.py
.
See also
-
See a complete Python example of how to connect to a database, load data into a collection, and perform a similarity search.
-
Read the Python client reference for more details about available methods.
-
Also see the Python tab for details and examples in each task-based section of the API Reference topics: