Hyper-Converged Database (HCD) 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 demonstrates how to create a collection, insert data with vector embeddings to the collection, 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 wideand 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 svcand look for the "PORT(S)" value that corresponds toNodePort.
For this quickstart, store the endpoint in an environment variable:
- Linux or macOS
-
export API_ENDPOINT=API_ENDPOINT - Windows
-
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
-
export USERNAME=USERNAME export PASSWORD=PASSWORD - Windows
-
set USERNAME=USERNAMEset PASSWORD=PASSWORD
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"
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
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")
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
Create a keyspace
The following code creates a new keyspace in your database.
This code creates a keyspace named quickstart_keyspace.
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 keyspace name in the subsequent code examples.
-
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.
Once the code completes, you should see a printed message confirming keyspace creation.
from quickstart_connect import connect_to_database
def main() -> None:
database = connect_to_database()
# Get an admin object
admin = database.get_database_admin()
# Create a keyspace
admin.create_keyspace("quickstart_keyspace")
print(f"Created keyspace")
if __name__ == "__main__":
main()
Create a collection
The following code creates an empty collection in your database. The collection stores 5-dimensional vector data and uses the cosine similarity metric for comparisons.
-
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,
)
from quickstart_connect import connect_to_database
def main() -> None:
database = connect_to_database()
collection = database.create_collection(
"quickstart_collection",
keyspace="quickstart_keyspace",
definition=CollectionDefinition(
vector=CollectionVectorOptions(
dimension=5,
metric=VectorMetric.COSINE,
),
),
)
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.
-
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", keyspace="quickstart_keyspace"
)
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
documents = [
{
**data,
# Convert the date string into a DataAPIDate
"due_date": (
DataAPIDate.from_string(data["due_date"])
if data.get("due_date")
else None
),
# Populate the reserved $vector field
"$vector": data["summary_genres_vector"],
}
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 vector.
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", keyspace="quickstart_keyspace"
)
# 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 given vector
print("\nUsing vector search to find a book...")
single_vector_match = collection.find_one(
sort={
"$vector": [
0.016326904,
-0.031677246,
0.04815674,
0.0033435822,
0.01876831,
]
}
)
print(f"{single_vector_match['title']} is the best match")
# Combine a filter, vector search, and projection to find the 3 books with
# more than 400 pages that are the closest matches to a given vector,
# and just return the title and author
print(
"\nUsing filters and vector search to find 3 books with more than 400 pages, returning just the title and author..."
)
vector_cursor = collection.find(
{"number_of_pages": {"$gt": 400}},
sort={
"$vector": [
0.016326904,
-0.031677246,
0.04815674,
0.0033435822,
0.01876831,
]
},
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.
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.
- 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 a document (Python), Find documents (Python), and Find data with vector search.