Before using upstash-vector, you’ll need to set up a vector database on Upstash. Once created, grab your URL and TOKEN from the Upstash console.To initialize the index client:
Copy
Ask AI
from upstash_vector import Indexindex = Index(url="UPSTASH_VECTOR_REST_URL", token="UPSTASH_VECTOR_REST_TOKEN")
Alternatively, you can automatically load the credentials from the environment:
Copy
Ask AI
from upstash_vector import Indexindex = Index.from_env()
For serverless environments that allow it, it’s recommended to initialize the client outside the request handler to be reused while your function is still “hot.”Here’s an example of how you can use the SDK in your Python application:
Copy
Ask AI
import randomfrom upstash_vector import Index# Initialize the index client using environment variablesindex = Index.from_env()def main(): # Define the dimension based on the index configuration dimension = 128 # Generate a random vector for upsert vector_to_upsert = [random.random() for _ in range(dimension)] # Additional metadata associated with the vector metadata = {"text": "example test for metadata"} # Upsert the vector into the index index.upsert(vectors=[ ("id-for-vector", vector_to_upsert, metadata) ])
The example above demonstrates how to upsert a vector with metadata using the SDK into the Upstash Vector database.