Upstash Vector Python SDK

0.8.0 · active · verified Thu Apr 16

The `upstash-vector` SDK is a lightweight, HTTP-based Upstash Vector client designed for Python. It seamlessly operates in both serverless and serverful environments, ensuring optimal compatibility across various connection setups. This SDK simplifies interaction with Upstash Vector through the Upstash Vector API. It is designed to work with Python versions 3.8 and above.

Common errors

Warnings

Install

Imports

Quickstart

Initializes the Upstash Vector client, upserts a sample vector with metadata, fetches it, and performs a similarity query. Credentials are loaded from environment variables (preferred) or can be replaced with direct values. Ensure your Upstash Vector index is created with the correct dimension.

import os
import random
from upstash_vector import Index

# Initialize the index client using environment variables
# Ensure UPSTASH_VECTOR_REST_URL and UPSTASH_VECTOR_REST_TOKEN are set
index = Index(
    url=os.environ.get('UPSTASH_VECTOR_REST_URL', 'YOUR_UPSTASH_VECTOR_REST_URL'),
    token=os.environ.get('UPSTASH_VECTOR_REST_TOKEN', 'YOUR_UPSTASH_VECTOR_REST_TOKEN')
)

def main():
    # Define the dimension based on your index configuration (e.g., 128)
    dimension = 128 

    # Generate a random vector for upsert
    vector_to_upsert = [random.random() for _ in range(dimension)]
    
    # Additional metadata associated with the vector (optional)
    metadata = {"text": "example test for metadata", "source": "quickstart"}
    
    # Upsert the vector into the index
    response = index.upsert(vectors=[
        ("id-for-vector-1", vector_to_upsert, metadata)
    ])
    print(f"Upsert response: {response}")

    # Fetch the upserted vector
    fetched_vectors = index.fetch(ids=["id-for-vector-1"], include_vectors=True, include_metadata=True)
    if fetched_vectors and fetched_vectors[0]:
        print(f"Fetched vector: {fetched_vectors[0].id}, Metadata: {fetched_vectors[0].metadata}")
    else:
        print("Vector not found or fetch failed.")

    # Query for similar vectors
    query_vector = [random.random() for _ in range(dimension)] # Example query vector
    query_results = index.query(
        vector=query_vector,
        top_k=1,
        include_vectors=False,
        include_metadata=True
    )
    print(f"Query results: {query_results}")

if __name__ == "__main__":
    main()

view raw JSON →