Astra DB Serverless quickstart for collections (Python)
|
If your data is fully structured and you want to use a fixed schema, see the quickstart for tables instead. This quickstart requires a Serverless (vector) database. For Serverless (non-vector) databases, see Get started with the Data API (Python). |
This quickstart demonstrates how to create a collection, insert data to the collection, 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
-
Click Create database.
-
For this quickstart, select the following:
-
Type: Serverless (vector)
-
Provider: Amazon Web Services
-
Region: us-east-2
-
-
If applicable to your organization, you can select or create a PCU group for the database.
-
Click Create database.
Wait for your database to initialize and reach Active status. This can take several minutes.
-
Under Database Details, copy your database’s API endpoint.
-
Under Database Details, click Generate Token, then copy the token.
-
For this quickstart, store the endpoint and token in environment variables:
- Linux or macOS
-
export API_ENDPOINT=API_ENDPOINT export APPLICATION_TOKEN=APPLICATION_TOKEN - Windows
-
set API_ENDPOINT=API_ENDPOINTset APPLICATION_TOKEN=APPLICATION_TOKEN
Install a client
Install one of the Data API clients to facilitate interactions with the Data API.
-
Update to Python version 3.10 to 3.14 or later if needed.
-
Update to pip version 23.0 or later if needed.
-
Install the latest version of the astrapy package.
pip install "astrapy>=2.0,<3.0"
To test pre-generated commands without installing a client, you can use the Data API console in the Astra Portal. The scripts used in this quickstart aren’t compatible with the Data API console because they are intended for use with a Data API client.
Connect to your database
The following function connects to your database.
Copy the file into your project. You don’t need to execute the function now; the subsequent code examples import and use this function.
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")
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
Create a collection
The following code creates an empty collection in your database.
The collection uses 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.
-
Copy the code into your project.
-
If needed, update the import path to the
connect_to_databasefunction from the previous section. -
This code creates a collection named
quickstart_collection. If you want to use a different name, change the name before running the code. If you change the name, you must also change the collection name in the subsequent code examples. -
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 collection creation.
from astrapy.constants import VectorMetric
from astrapy.info import (
CollectionDefinition,
CollectionVectorOptions,
VectorServiceOptions,
)
from quickstart_connect import connect_to_database
def main() -> None:
database = connect_to_database()
collection = database.create_collection(
"quickstart_collection",
definition=CollectionDefinition(
vector=CollectionVectorOptions(
metric=VectorMetric.COSINE,
service=VectorServiceOptions(
provider="nvidia",
model_name="nvidia/nv-embedqa-e5-v5",
),
)
),
)
print(f"Created collection {collection.full_name}")
if __name__ == "__main__":
main()
Insert data to your collection
The following code inserts data from a JSON file to your collection.
When you insert data to a collection that can automatically generate embeddings, you can specify a $vectorize value for the data.
The $vectorize value is used to generate vector embeddings.
$vectorize can be any string and should include the parts of the data that you want to be considered when you search for similar data with a vector search.
-
Copy the code into your project.
-
Download the quickstart_dataset.json sample dataset (76 kB). This dataset is a JSON array describing library books.
-
Replace
PATH_TO_DATA_FILEin the code with the path to the dataset. -
If needed, update the import path to the
connect_to_databasefunction from the previous section. -
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 documents.
import json
from astrapy.data_types import DataAPIDate
from quickstart_connect import connect_to_database
def main() -> None:
database = connect_to_database()
collection = database.get_collection("quickstart_collection")
data_file_path = "PATH_TO_DATA_FILE"
# Read the JSON file and parse it into a JSON array
with open(data_file_path, "r", encoding="utf8") as file:
json_data = json.load(file)
# Assemble the documents to insert:
# - Convert the date string into a DataAPIDate
# - Add a $vectorize field
documents = [
{
**data,
"due_date": (
DataAPIDate.from_string(data["due_date"])
if data.get("due_date")
else None
),
"$vectorize": (
f"summary: {data['summary']} | genres: {', '.join(data['genres'])}"
),
}
for data in json_data
]
# Insert the data
inserted = collection.insert_many(documents)
print(f"Inserted {len(inserted.inserted_ids)} documents.")
if __name__ == "__main__":
main()
Find data in your collection
After you insert data to your collection, 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 code performs three searches on the sample data that you loaded in Insert data to your collection.
-
Copy the code into your project.
-
If needed, update the import path to the
connect_to_databasefunction from the previous section. -
Execute the code.
For information about executing code, refer to the documentation for your programming language.
As the code executes, it prints details about the found data.
from quickstart_connect import connect_to_database
def main() -> None:
database = connect_to_database()
collection = database.get_collection("quickstart_collection")
# Find documents that match a filter
print("\nFinding books with rating greater than 4.7...")
rating_cursor = collection.find({"rating": {"$gt": 4.7}})
for document in rating_cursor:
print(f"{document['title']} is rated {document['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 = collection.find_one(
sort={"$vectorize": "A scary novel"}
)
print(f"{single_vector_match['title']} is a scary novel")
# Combine a filter, vector search, and projection to find the 3 books with
# more than 400 pages that are the closest matches to a search string,
# and just return the title and author
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 = collection.find(
{"number_of_pages": {"$gt": 400}},
sort={"$vectorize": "A book set in the arctic"},
limit=3,
projection={"title": True, "author": True},
)
for document in vector_cursor:
print(document)
if __name__ == "__main__":
main()
Next steps
For more practice, you can continue building with the collection that you created here. For example, try inserting more data to the collection, 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 data from a JSON file, but you can insert data from many sources, including CSV and PDF files.
-
If you can convert your data into JSON, you can use the example from this quickstart.
-
If your data is in unstructured files, such as PDF files, you can use the Astra Portal or write code to use the Unstructured.io integration to insert your data.
This quickstart also demonstrated how to insert data to a collection, which uses a flexible schema. If your data is structured and you want to use a fixed schema, you can use a table instead of a collection. See the quickstart for tables.
-
- 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.
-
To use a different embedding model, see Generate and store embeddings in Astra DB Serverless databases.
-
To insert pre-embedded data, you need to specify the vector dimensions and similarity metric instead of specifying the embedding provider. See the API documentation for collections.
-
To skip embedding, you can create a collection without any vector options. See the API documentation 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 Ways to find data in Astra DB Serverless.
- 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. For more information, see Astra DB Serverless database regions and maintenance schedules and Create an Astra DB Serverless database.
- More tutorials and examples
-
Try building a chatbot that uses this collection for retrieval-augmented generation (RAG) with OpenAI: Build a RAG command line chatbot (Python).
For more examples, see the integration guides, code examples, and tutorials.