TITLE: Implementing Semantic Search with Upstash Vector in Python
DESCRIPTION: This Python script demonstrates how to use Upstash Vector for semantic search. It includes initializing the index, inserting documents, and performing a search query. The script also handles environment variables and displays search results.
SOURCE: https://github.com/upstash/docs/blob/main/vector/tutorials/semantic_search.mdx#2025-04-11_snippet_2
LANGUAGE: python
CODE:
```
from upstash_vector import Index
from dotenv import load_dotenv
import time
# Load environment variables from a .env file
load_dotenv()
# Initialize the index from environment variables (URL and token)
index = Index.from_env()
# Example documents to be indexed
documents = [
{"id": "1", "text": "Python is a popular programming language."},
{"id": "2", "text": "Machine learning enables computers to learn from data."},
{"id": "3", "text": "Upstash provides low-latency database solutions."},
{"id": "4", "text": "Semantic search is a technique for understanding the meaning of queries."},
{"id": "5", "text": "Cloud computing allows for scalable and flexible resource management."}
]
# Reset the index to remove previous data
index.reset()
# Upsert documents into Upstash (embeddings are generated automatically)
for doc in documents:
index.upsert(
vectors=[
(doc["id"], doc["text"], {"text": doc["text"]})
]
)
print(f"Document {doc['id']} inserted.")
# Wait for the documents to be indexed
time.sleep(1)
# Search for documents similar to the query
query = "What is Python?"
results = index.query(data=query, top_k=3, include_metadata=True)
# Display search results
print("Search Results:")
for result in results:
print(f"ID: {result.id}")
print(f"Score: {result.score:.4f}")
print(f"Metadata: {result.metadata}")
print("-" * 40) # Separator line between results
```
----------------------------------------
TITLE: Inserting Data into Upstash Vector Index using Python
DESCRIPTION: Code for upserting vector data into an Upstash Vector Index using the Python SDK. It demonstrates how to create an Index instance with authentication credentials and insert a vector with ID, embedding values, and metadata.
SOURCE: https://github.com/upstash/docs/blob/main/vector/overall/getstarted.mdx#2025-04-11_snippet_0
LANGUAGE: python
CODE:
```
from upstash_vector import Index
index = Index(url="UPSTASH_VECTOR_REST_URL", token="UPSTASH_VECTOR_REST_TOKEN")
index.upsert(
vectors=[
("1", [0.6, 0.8], {"field": "value"}),
]
)
```
----------------------------------------
TITLE: Installing Required Packages for LangChain and Upstash Vector
DESCRIPTION: This command installs the necessary Python packages to use LangChain with Upstash Vector, including upstash-vector, langchain, langchain-community, and python-dotenv.
SOURCE: https://github.com/upstash/docs/blob/main/vector/integrations/langchain.mdx#2025-04-11_snippet_0
LANGUAGE: bash
CODE:
```
pip install upstash-vector langchain langchain-community python-dotenv
```
----------------------------------------
TITLE: Complete Example of Resumable Query Usage in Python for Upstash Vector Database
DESCRIPTION: This comprehensive example demonstrates the entire process of using resumable queries, including creating an index, upserting vectors, starting a query, fetching results, and stopping the query.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/py/example_calls/resumable-query.mdx#2025-04-11_snippet_5
LANGUAGE: python
CODE:
```
from upstash_vector import Index
# Create an index instance
index = Index()
# Upsert vectors into the index
index.upsert(
vectors=[
("id1", [0.1, 0.2], {"field": "value1"}),
("id2", [0.3, 0.4], {"field": "value2"}),
("id3", [0.5, 0.6], {"field": "value3"}),
],
namespace="example-namespace"
)
# Start a resumable query
query = index.resumable_query(
vector=[0.1, 0.2],
top_k=2,
include_metadata=True,
include_vectors=True,
namespace="example-namespace"
)
# Fetch initial results
results = query.start()
# Access result data
for result in results:
print(f"ID: {result.id}, Metadata: {result.metadata}")
# Stop the query when done
query.stop()
```
----------------------------------------
TITLE: Using Namespaces with Upstash Vector Store
DESCRIPTION: Example of creating an Upstash Vector Store with a specific namespace to separate different types of documents. Namespaces allow organization of vector data within the same index.
SOURCE: https://github.com/upstash/docs/blob/main/vector/tutorials/langchain.mdx#2025-04-11_snippet_6
LANGUAGE: python
CODE:
```
store = UpstashVectorStore(embedding=True, namespace="my_namespace")
```
----------------------------------------
TITLE: Initializing Upstash Vector Index with Credentials
DESCRIPTION: Code to initialize the Vector Index client by directly providing the REST URL and token obtained from the Upstash console. This is the standard way to connect to your Upstash Vector database.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/py/gettingstarted.mdx#2025-04-11_snippet_1
LANGUAGE: python
CODE:
```
from upstash_vector import Index
index = Index(url="UPSTASH_VECTOR_REST_URL", token="UPSTASH_VECTOR_REST_TOKEN")
```
----------------------------------------
TITLE: Installing LlamaIndex with Upstash Vector Dependencies
DESCRIPTION: This command installs the necessary Python packages for using LlamaIndex with Upstash Vector, including the core libraries and vector store integration components.
SOURCE: https://github.com/upstash/docs/blob/main/vector/integrations/llamaindex.mdx#2025-04-11_snippet_0
LANGUAGE: bash
CODE:
```
pip install llama-index upstash-vector llama-index-vector-stores-upstash python-dotenv
```
----------------------------------------
TITLE: Querying Vectors with Custom Namespace in Python
DESCRIPTION: This short snippet shows how to query vectors from a specific namespace in Upstash Vector. When no namespace is provided, the default namespace is used.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/py/example_calls/query.mdx#2025-04-11_snippet_2
LANGUAGE: python
CODE:
```
index.query(..., namespace="ns")
```
----------------------------------------
TITLE: Performing Similarity Search with Upstash Vector and OpenAI in Python
DESCRIPTION: This snippet demonstrates how to perform a similarity search using the Upstash Vector Database and OpenAI embeddings. It generates an embedding for the query, searches the database for similar vectors, and returns the top results along with their metadata.
SOURCE: https://github.com/upstash/docs/blob/main/vector/overall/llms-txt.mdx#2025-04-11_snippet_2
LANGUAGE: python
CODE:
```
def search(query: str, top_k: int = 5):
embedding = openai.Embedding.create(input=[query], engine="text-embedding-ada-002")['data'][0]['embedding']
results = index.query(vector=embedding, top_k=top_k, include_metadata=True)
return [(result.id, result.score, result.metadata['text']) for result in results]
# Example usage
query = "What is Upstash Vector?"
results = search(query)
for id, score, text in results:
print(f"ID: {id}, Score: {score}, Text: {text}")
```
----------------------------------------
TITLE: Implementing Question Answering with Gradio Interface
DESCRIPTION: Setting up a Question Answering pipeline with HuggingFace and creating a Gradio interface. This code configures the QA model, defines a function to retrieve relevant documents and generate answers, and creates an interactive web interface.
SOURCE: https://github.com/upstash/docs/blob/main/vector/tutorials/gradio-application.mdx#2025-04-11_snippet_4
LANGUAGE: python
CODE:
```
# Set up a Hugging Face Question Answering model
qa_pipeline = pipeline("question-answering", model="distilbert-base-cased-distilled-squad")
# Gradio interface function
def answer_question(query):
# Retrieve relevant documents from Upstash Vector
results = vector_store.similarity_search(query, k=3)
# Use the most relevant document for QA
if results:
context = results[0].page_content
qa_input = {"question": query, "context": context}
answer = qa_pipeline(qa_input)["answer"]
return f"Answer: {answer}\n\nContext: {context}"
else:
return "No relevant context found."
# Set up Gradio interface
iface = gr.Interface(
fn=answer_question,
inputs="text",
outputs="text",
title="RAG Application",
description="Ask a question, and the app will retrieve relevant information and provide an answer."
)
# Launch the Gradio app
iface.launch()
```
----------------------------------------
TITLE: Initializing Upstash Vector Store and Creating a Document Index
DESCRIPTION: Python code that initializes an Upstash Vector store, loads documents from a directory, and creates a vector index. This setup forms the foundation for the RAG system.
SOURCE: https://github.com/upstash/docs/blob/main/vector/integrations/llamaindex.mdx#2025-04-11_snippet_2
LANGUAGE: python
CODE:
```
from llama_index.core import VectorStoreIndex, SimpleDirectoryReader
from llama_index.vector_stores.upstash import UpstashVectorStore
from llama_index.core import StorageContext
import os
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
# Set OpenAI API key
openai.api_key = os.environ["OPENAI_API_KEY"]
# Initialize Upstash Vector store
upstash_vector_store = UpstashVectorStore(
url=os.environ["UPSTASH_VECTOR_REST_URL"],
token=os.environ["UPSTASH_VECTOR_REST_TOKEN"],
)
# Load documents using SimpleDirectoryReader
documents = SimpleDirectoryReader("./documents/").load_data()
# Create a storage context and initialize the index
storage_context = StorageContext.from_defaults(vector_store=upstash_vector_store)
index = VectorStoreIndex.from_documents(
documents, storage_context=storage_context
)
```
----------------------------------------
TITLE: Querying the vector index for RAG-based responses
DESCRIPTION: Python code that initializes a query engine from the vector index and uses it to execute queries about global warming. The system retrieves relevant content from the indexed document to generate contextually relevant responses.
SOURCE: https://github.com/upstash/docs/blob/main/vector/tutorials/llamaindex.mdx#2025-04-11_snippet_3
LANGUAGE: python
CODE:
```
# Initialize the query engine
query_engine = index.as_query_engine()
# Query the document about global warming
res1 = query_engine.query("What is global warming?")
print(res1)
res2 = query_engine.query("How should we modify our diets to reduce our carbon footprint?")
print(res2)
```
----------------------------------------
TITLE: Initializing Upstash Vector Client from Environment Variables
DESCRIPTION: Code example showing how to initialize the Upstash Vector client using environment variables that have been previously set.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/php/getting-started.mdx#2025-04-11_snippet_2
LANGUAGE: php
CODE:
```
use Upstash\Vector\Index;
$index = Index::fromEnv();
```
----------------------------------------
TITLE: Displaying Similarity Search Results from LangChain and Upstash Vector
DESCRIPTION: This output shows the results of a similarity search performed using LangChain and Upstash Vector. It displays the most relevant documents retrieved based on the query 'What is LangChain?'.
SOURCE: https://github.com/upstash/docs/blob/main/vector/integrations/langchain.mdx#2025-04-11_snippet_2
LANGUAGE: plaintext
CODE:
```
Similarity Search Results:
LangChain is a framework for building intelligent apps.
Semantic search enables advanced query matching.
Upstash Vector is a scalable vector database.
```
----------------------------------------
TITLE: Querying Hybrid Index using Reciprocal Rank Fusion in JavaScript
DESCRIPTION: This code example shows how to query a hybrid index using the Reciprocal Rank Fusion (RRF) algorithm in JavaScript. It creates an Index instance and performs a query with both dense and sparse vectors, setting RRF as the fusion algorithm.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/hybridindexes.mdx#2025-04-11_snippet_5
LANGUAGE: javascript
CODE:
```
import { FusionAlgorithm, Index } from "@upstash/vector";
const index = new Index({
url: "UPSTASH_VECTOR_REST_URL",
token: "UPSTASH_VECTOR_REST_TOKEN",
});
await index.query({
vector: [0.5, 0.4],
sparseVector: {
indices: [2, 3],
values: [0.13, 0.87],
},
fusionAlgorithm: FusionAlgorithm.RRF,
topK: 3,
});
```
----------------------------------------
TITLE: Implementing Chat API Route with OpenAI and Upstash Vector
DESCRIPTION: Backend implementation of the chat API route that handles conversation state, AI model configuration, and tool definitions for resource management and content retrieval using Upstash Vector.
SOURCE: https://github.com/upstash/docs/blob/main/vector/integrations/ai-sdk.mdx#2025-04-11_snippet_5
LANGUAGE: typescript
CODE:
```
import { openai } from '@ai-sdk/openai'
import { streamText, tool } from 'ai'
import { z } from 'zod'
// Tools
import { createResource } from '@/lib/actions/resources'
import { findRelevantContent } from '@/lib/ai/upstashVector'
// Allow streaming responses up to 30 seconds
export const maxDuration = 30
export async function POST(req: Request) {
const { messages } = await req.json()
const result = streamText({
// 1. Choose your AI model
model: openai('gpt-4o'),
// 2. Pass along the conversation messages from the user
messages,
// 3. Prompt the model
system: `You are a helpful RAG assistant.
You have the ability to add and retrieve content from your knowledge base.
Only respond to the user with information found in your knowledge base.
If no relevant information is found, respond with: "Sorry, I don't know."`,
// 4. Provide your "tools": resource creation & retrieving content
tools: {
addResource: tool({
description: `Add new content to the knowledge base.`,
parameters: z.object({
content: z.string().describe('The content to embed and store'),
}),
execute: async ({ content }) => {
const msg = await createResource({ content })
return msg
},
}),
getInformation: tool({
description: `Retrieve relevant knowledge from your knowledge base to answer user queries.`,
parameters: z.object({
question: z.string().describe('The question to search for'),
}),
execute: async ({ question }) => {
const hits = await findRelevantContent(question)
// Return array of metadata for each chunk
// e.g. [{ id, score, metadata: { resourceId, content }}, ... ]
return hits
},
}),
},
})
// 5. Return the streaming response
return result.toDataStreamResponse()
}
```
----------------------------------------
TITLE: Implementing Custom Reranking for Hybrid Index in Python
DESCRIPTION: This Python code snippet demonstrates how to implement custom reranking for a hybrid index. It performs separate queries for dense and sparse components, allowing for custom reranking of the results.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/hybridindexes.mdx#2025-04-11_snippet_14
LANGUAGE: python
CODE:
```
from upstash_vector import Index
from upstash_vector.types import SparseVector
index = Index(
url="UPSTASH_VECTOR_REST_URL",
token="UPSTASH_VECTOR_REST_TOKEN",
)
dense_results = index.query(
vector=[0.5, 0.4],
)
sparse_results = index.query(
sparse_vector=SparseVector([3, 5], [0.3, 0.5]),
)
# Rerank dense and sparse results as you like here
```
----------------------------------------
TITLE: Document Querying with Upstash Vector and OpenAI
DESCRIPTION: Implementation of document querying using Upstash Vector store and OpenAI, including environment setup and query execution.
SOURCE: https://github.com/upstash/docs/blob/main/vector/tutorials/llamaparse.mdx#2025-04-11_snippet_4
LANGUAGE: python
CODE:
```
from llama_index.core import VectorStoreIndex
from llama_index.vector_stores.upstash import UpstashVectorStore
from llama_index.core import StorageContext
import openai
# Load environment variables for API keys and Upstash configuration
from dotenv import load_dotenv
import os
load_dotenv()
# Set up OpenAI API key
openai.api_key = os.getenv("OPENAI_API_KEY")
# Set up Upstash Vector Store
upstash_vector_store = UpstashVectorStore(
url=os.getenv("UPSTASH_VECTOR_REST_URL"),
token=os.getenv("UPSTASH_VECTOR_REST_TOKEN"),
)
# Create a storage context for Upstash Vector and index the parsed document
storage_context = StorageContext.from_defaults(vector_store=upstash_vector_store)
index = VectorStoreIndex.from_documents(documents, storage_context=storage_context)
# Create a query engine for the index and perform a query
query_engine = index.as_query_engine()
query = "What are the main points discussed in the document?"
response = query_engine.query(query)
print(response)
```
----------------------------------------
TITLE: Querying Text Data with Embedding Models in Python
DESCRIPTION: Shows how to query Upstash Vector with raw text in Python. The query text will be automatically converted to a vector embedding by the selected model for similarity search.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/embeddingmodels.mdx#2025-04-11_snippet_5
LANGUAGE: python
CODE:
```
from upstash_vector import Index
index = Index(
url="UPSTASH_VECTOR_REST_URL",
token="UPSTASH_VECTOR_REST_TOKEN",
)
index.query(
data="What is Upstash?",
top_k=1,
include_metadata=True,
)
```
----------------------------------------
TITLE: Initializing Upstash Vector Store with LangChain
DESCRIPTION: Code to load environment variables and initialize an Upstash Vector store instance with automatic embedding generation. This setup enables vector-based similarity searches.
SOURCE: https://github.com/upstash/docs/blob/main/vector/tutorials/langchain.mdx#2025-04-11_snippet_2
LANGUAGE: python
CODE:
```
from dotenv import load_dotenv
from langchain_community.vectorstores.upstash import UpstashVectorStore
load_dotenv()
# Create a vector store instance where embeddings are generated by Upstash
store = UpstashVectorStore(embedding=True)
```
----------------------------------------
TITLE: Querying the LlamaIndex Vector Store for RAG Responses
DESCRIPTION: Example of how to create a query engine from the index and perform queries against it. The query engine retrieves relevant document sections and generates coherent responses.
SOURCE: https://github.com/upstash/docs/blob/main/vector/integrations/llamaindex.mdx#2025-04-11_snippet_3
LANGUAGE: python
CODE:
```
# Initialize the query engine
query_engine = index.as_query_engine()
# Perform queries
response_1 = query_engine.query("What is global warming?")
print(response_1)
response_2 = query_engine.query("How can we reduce our carbon footprint?")
print(response_2)
```
----------------------------------------
TITLE: Batch Querying Vector Data with curl in Upstash
DESCRIPTION: Advanced curl command demonstrating batch querying of vector data by sending an array of query objects, each with its own parameters.
SOURCE: https://github.com/upstash/docs/blob/main/vector/api/endpoints/query-data.mdx#2025-04-11_snippet_2
LANGUAGE: sh
CODE:
```
curl $UPSTASH_VECTOR_REST_URL/query-data \
-X POST \
-H "Authorization: Bearer $UPSTASH_VECTOR_REST_TOKEN" \
-d '[\n {\n "data": "What is Upstash?",\n "topK": 2,\n "includeMetadata": true\n },\n {\n "data": "What is Upstash Vector?",\n "topK": 3\n }\n ]'
```
----------------------------------------
TITLE: Using LangChain with Upstash Vector for Document Storage and Similarity Search
DESCRIPTION: This Python script demonstrates how to create an Upstash Vector store, add documents to it, and perform a similarity search using LangChain. It includes environment variable loading, vector store initialization, document addition, and query execution.
SOURCE: https://github.com/upstash/docs/blob/main/vector/integrations/langchain.mdx#2025-04-11_snippet_1
LANGUAGE: python
CODE:
```
from dotenv import load_dotenv
from langchain_community.vectorstores.upstash import UpstashVectorStore
from langchain.schema import Document
# Load environment variables
load_dotenv()
# Create a vector store instance
store = UpstashVectorStore(
embedding=True, # Embedding option enabled
)
# Sample documents to upload
documents = [
Document(page_content="Upstash Vector is a scalable vector database."),
Document(page_content="LangChain is a framework for building intelligent apps."),
Document(page_content="Semantic search enables advanced query matching."),
]
# Add documents to the Upstash Vector index
store.add_documents(documents)
# Perform a similarity search
query = "What is LangChain?"
results = store.similarity_search(query, k=3)
print("Similarity Search Results:")
for res in results:
print(res.page_content)
```
----------------------------------------
TITLE: Indexing Documents in Upstash Vector Database using Python
DESCRIPTION: This code snippet shows how to index documents in the Upstash Vector Database. It uses the OpenAI library to generate embeddings for the documents and then upserts them into the database. The function takes a list of documents and processes them in batches.
SOURCE: https://github.com/upstash/docs/blob/main/vector/overall/llms-txt.mdx#2025-04-11_snippet_1
LANGUAGE: python
CODE:
```
import openai
from typing import List
openai.api_key = os.environ["OPENAI_API_KEY"]
def index_documents(documents: List[str]):
batch_size = 100
for i in range(0, len(documents), batch_size):
batch = documents[i:i+batch_size]
ids = list(range(i, i+len(batch)))
embeddings = openai.Embedding.create(input=batch, engine="text-embedding-ada-002")['data']
vectors = [embedding['embedding'] for embedding in embeddings]
metadata = [{"text": doc} for doc in batch]
index.upsert(vectors=vectors, ids=ids, metadata=metadata)
print(f"Indexed {len(batch)} documents")
# Example usage
documents = ["Hello world", "Upstash Vector is awesome", "LLMs are the future"]
index_documents(documents)
```
----------------------------------------
TITLE: Adding Documents to Upstash Vector Store
DESCRIPTION: Code to insert document chunks into the Upstash Vector index. This process converts the text chunks into vector embeddings and stores them for later similarity searches.
SOURCE: https://github.com/upstash/docs/blob/main/vector/tutorials/langchain.mdx#2025-04-11_snippet_4
LANGUAGE: python
CODE:
```
inserted_vectors = store.add_documents(docs)
```
----------------------------------------
TITLE: Querying Upstash Vector Index using Python
DESCRIPTION: Code for performing a similarity search in an Upstash Vector Index using the Python SDK. It demonstrates how to query the index with a vector, limit results, and include metadata in the response.
SOURCE: https://github.com/upstash/docs/blob/main/vector/overall/getstarted.mdx#2025-04-11_snippet_5
LANGUAGE: python
CODE:
```
from upstash_vector import Index
index = Index(url="UPSTASH_VECTOR_REST_URL", token="UPSTASH_VECTOR_REST_TOKEN")
index.query(
vector=[0.6, 0.8],
top_k=3,
include_metadata=True,
)
```
----------------------------------------
TITLE: Setting Up Embeddings and Vector Store in Python
DESCRIPTION: Initializing the embedding model and Upstash Vector store. This code imports required libraries, loads environment variables, and configures the HuggingFace embeddings model with Upstash Vector storage.
SOURCE: https://github.com/upstash/docs/blob/main/vector/tutorials/gradio-application.mdx#2025-04-11_snippet_2
LANGUAGE: python
CODE:
```
# Import libraries
import gradio as gr
from dotenv import load_dotenv
from langchain_huggingface.embeddings import HuggingFaceEmbeddings
from langchain_community.vectorstores.upstash import UpstashVectorStore
from transformers import pipeline
from langchain.schema import Document
# Load environment variables
load_dotenv()
# Set up embeddings and Upstash Vector store
embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-mpnet-base-v2")
vector_store = UpstashVectorStore(embedding=embeddings)
```
----------------------------------------
TITLE: Querying Upstash Vector Index Using Vector Embeddings in TypeScript
DESCRIPTION: This snippet demonstrates how to query an Upstash Vector index by providing a vector embedding directly. It specifies topK to limit results, includes metadata and vector data in the response, and uses a custom namespace.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/ts/commands/query.mdx#2025-04-11_snippet_0
LANGUAGE: typescript
CODE:
```
await index.query({
topK: 2,
vector: [ ... ],
includeMetadata: true,
includeVectors: true
}, { namespace: "my-namespace" })
/*
[
{
id: '6345',
score: 0.85,
vector: [],
metadata: {
sentence: "Upstash is great."
}
},
{
id: '1233',
score: 0.75,
vector: [],
metadata: undefined
},
]
*/
```
----------------------------------------
TITLE: Fetching Multiple Vectors with Upstash Vector in Python
DESCRIPTION: Example of fetching multiple vectors from an Upstash Vector index using a list of identifiers. This snippet demonstrates how to retrieve vectors with their associated data and metadata included in the results and how to process the returned vector information.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/py/example_calls/fetch.mdx#2025-04-11_snippet_0
LANGUAGE: python
CODE:
```
from upstash_vector import Index
index = Index.from_env()
# Specify the identifiers of vectors to be fetched
ids_to_fetch = ["id-1", "id-2", "id-3"]
# Fetch the specified vectors with vectors and metadata included
fetch_result = index.fetch(
ids=ids_to_fetch,
include_vectors=True,
include_metadata=True,
include_data=True,
)
# Display the fetched vectors
for vector_info in fetch_result:
print("ID:", vector_info.id)
print("Vector:", vector_info.vector)
print("Metadata:", vector_info.metadata)
print("Data:", vector_info.data)
```
----------------------------------------
TITLE: Adding Document Embeddings to Upstash Vector
DESCRIPTION: Creating sample documents, embedding them using HuggingFace embeddings, and storing them in Upstash Vector with batch processing configuration. The code demonstrates how to control batch size and embedding chunk size for performance optimization.
SOURCE: https://github.com/upstash/docs/blob/main/vector/tutorials/gradio-application.mdx#2025-04-11_snippet_3
LANGUAGE: python
CODE:
```
# Sample documents to embed and store
documents = [
Document(page_content="Global warming is causing sea levels to rise."),
Document(page_content="AI is transforming many industries."),
Document(page_content="Renewable energy is vital for sustainable development.")
]
vector_store.add_documents(documents=documents, batch_size=100, embedding_chunk_size=200)
```
----------------------------------------
TITLE: Upserting Text Data with Embedding Models in Python
DESCRIPTION: Shows how to upsert raw text data into Upstash Vector using Python. The text will be automatically converted to vector embeddings by the selected model.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/embeddingmodels.mdx#2025-04-11_snippet_0
LANGUAGE: python
CODE:
```
from upstash_vector import Index
index = Index(
url="UPSTASH_VECTOR_REST_URL",
token="UPSTASH_VECTOR_REST_TOKEN",
)
index.upsert(
[("id-0", "Upstash is a serverless data platform.", {"field": "value"})],
)
```
----------------------------------------
TITLE: Querying Upstash Vector Index Using Raw Text Data in TypeScript
DESCRIPTION: This example shows how to query an Upstash Vector index by providing raw text data instead of vector embeddings. It uses metadata filtering to narrow results to fantasy movies with a specific title, and includes both vectors and metadata in the response.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/ts/commands/query.mdx#2025-04-11_snippet_1
LANGUAGE: typescript
CODE:
```
const results = await index.query({
data: "Movie about an adventure of a hobbit in a fantasy world.",
includeVectors: true,
includeMetadata: true,
topK: 1,
filter: "genre = 'fantasy' and title = 'Lord of the Rings'",
});
/*
[
{
id: "1234",
vector: [0.1, 0.2, 0.3, 0.4, 0.5],
score: 0.9999999,
metadata: {
title: "Lord of The Rings",
genre: "fantasy",
category: "classic",
},
}
]
*/
```
----------------------------------------
TITLE: Initializing LlamaIndex with Upstash Vector Store for document indexing
DESCRIPTION: Python code that loads environment variables, sets up the Upstash vector store, reads documents from a directory, initializes a storage context, and creates a vector index from the documents. This enables document embedding and retrieval for RAG.
SOURCE: https://github.com/upstash/docs/blob/main/vector/tutorials/llamaindex.mdx#2025-04-11_snippet_2
LANGUAGE: python
CODE:
```
from llama_index.core import VectorStoreIndex, SimpleDirectoryReader
from llama_index.vector_stores.upstash import UpstashVectorStore
from llama_index.core import StorageContext
import openai
import os
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
openai.api_key = os.environ["OPENAI_API_KEY"]
# Setup the Upstash vector store
upstash_vector_store = UpstashVectorStore(
url=os.environ["UPSTASH_VECTOR_REST_URL"],
token=os.environ["UPSTASH_VECTOR_REST_TOKEN"],
)
# Read the document about global warming from the documents directory
documents = SimpleDirectoryReader("./documents/").load_data()
# Initialize the storage context with the Upstash vector store
storage_context = StorageContext.from_defaults(vector_store=upstash_vector_store)
# Create the index from the loaded document with 1536 dimensions and cosine distance
index = VectorStoreIndex.from_documents(
documents, storage_context=storage_context
)
```
----------------------------------------
TITLE: Querying Hybrid Index using Distribution-Based Score Fusion in PHP
DESCRIPTION: This PHP code example demonstrates how to query a hybrid index using the Distribution-Based Score Fusion (DBSF) algorithm. It creates an Index object and performs a query with both dense and sparse vectors, setting DBSF as the fusion algorithm.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/hybridindexes.mdx#2025-04-11_snippet_12
LANGUAGE: php
CODE:
```
use Upstash\Vector\Index;
use Upstash\Vector\VectorQuery;
use Upstash\Vector\SparseVector;
use Upstash\Vector\Enums\FusionAlgorithm;
$index = new Index(
url: 'UPSTASH_VECTOR_REST_URL',
token: 'UPSTASH_VECTOR_REST_TOKEN',
);
$index->query(new VectorQuery(
vector: [0.5, 0.4],
sparseVector: new SparseVector(
indices: [3, 5],
values: [0.3, 0.5],
),
topK: 5,
includeMetadata: true,
fusionAlgorithm: FusionAlgorithm::DISTRIBUTION_BASED_SCORE_FUSION,
));
```
----------------------------------------
TITLE: Filtering Vectors by Metadata in PHP
DESCRIPTION: Example showing how to query vectors with metadata filtering in PHP. The filter uses a GLOB pattern to match only vectors with URLs containing 'imgur.com'.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/metadata.mdx#2025-04-11_snippet_14
LANGUAGE: php
CODE:
```
use Upstash\Vector\Index;
use Upstash\Vector\VectorQuery;
$index = new Index(
url: 'UPSTASH_VECTOR_REST_URL',
token: 'UPSTASH_VECTOR_REST_TOKEN',
);
$index->query(new VectorQuery(
vector: [0.9215, 0.3897],
topK: 5,
includeMetadata: true,
filter: "url GLOB '*imgur.com*'",
));
```
----------------------------------------
TITLE: Creating Chat UI Component with Vercel AI SDK
DESCRIPTION: Frontend implementation of the chat interface using the Vercel AI SDK's useChat hook, including message rendering and input handling.
SOURCE: https://github.com/upstash/docs/blob/main/vector/integrations/ai-sdk.mdx#2025-04-11_snippet_6
LANGUAGE: typescript
CODE:
```
'use client'
import { useChat } from 'ai/react'
export default function Home() {
// This hook handles message state + streaming from /api/chat
const { messages, input, handleInputChange, handleSubmit } = useChat({
// You can enable multi-step calls if you want the model to call multiple tools in one session
maxSteps: 3,
})
return (
RAG Chatbot with Upstash Vector
{/* Render messages */}
{messages.map(m => (
{m.role}:
{/* If the model calls a tool, show which tool it called */}
{m.content.length > 0 ? (
m.content
) : (
calling tool: {m?.toolInvocations?.[0]?.toolName}
)}
))}
{/* Text input */}
)
```
----------------------------------------
TITLE: Querying Hybrid Indexes with Vectors
DESCRIPTION: Examples demonstrating how to query hybrid indexes using both dense and sparse vectors with various configuration options like topK and metadata inclusion.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/hybridindexes.mdx#2025-04-11_snippet_2
LANGUAGE: python
CODE:
```
from upstash_vector import Index
from upstash_vector.types import SparseVector
index = Index(
url="UPSTASH_VECTOR_REST_URL",
token="UPSTASH_VECTOR_REST_TOKEN",
)
index.query(
vector=[0.5, 0.4],
sparse_vector=SparseVector([3, 5], [0.3, 0.5]),
top_k=5,
include_metadata=True,
)
```
LANGUAGE: javascript
CODE:
```
import { Index } from "@upstash/vector"
const index = new Index({
url: "UPSTASH_VECTOR_REST_URL",
token: "UPSTASH_VECTOR_REST_TOKEN",
})
await index.query({
vector: [0.5, 0.4],
sparseVector: {
indices: [2, 3],
values: [0.13, 0.87],
},
includeData: true,
topK: 3,
})
```
----------------------------------------
TITLE: Indexing and Querying Parsed Content with Upstash Vector in Python
DESCRIPTION: This snippet shows how to index parsed documents using Upstash Vector and perform semantic queries. It sets up the Upstash Vector Store, creates a storage context, indexes the documents, and executes a query.
SOURCE: https://github.com/upstash/docs/blob/main/vector/integrations/llamaparse.mdx#2025-04-11_snippet_3
LANGUAGE: python
CODE:
```
from llama_index.core import VectorStoreIndex
from llama_index.vector_stores.upstash import UpstashVectorStore
from llama_index.core import StorageContext
from dotenv import load_dotenv
import os
# Load environment variables
load_dotenv()
# Set up Upstash Vector Store
vector_store = UpstashVectorStore(
url=os.getenv("UPSTASH_VECTOR_REST_URL"),
token=os.getenv("UPSTASH_VECTOR_REST_TOKEN")
)
# Create storage context and index the parsed document
storage_context = StorageContext.from_defaults(vector_store=vector_store)
index = VectorStoreIndex.from_documents(documents, storage_context=storage_context)
# Perform a query
query_engine = index.as_query_engine()
response = query_engine.query("What is the main topic discussed in the document?")
```
----------------------------------------
TITLE: Querying Vectors with Metadata Filtering in Python
DESCRIPTION: This snippet demonstrates how to query vectors from an Upstash Vector index with similarity search. It creates a random query vector, executes the query with metadata filtering, and prints the results including score, ID, vector, metadata, and data for each returned item.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/py/example_calls/query.mdx#2025-04-11_snippet_0
LANGUAGE: python
CODE:
```
import random
from upstash_vector import Index
index = Index.from_env()
# Generate a random vector for similarity comparison
dimension = 128 # Adjust based on your index's dimension
query_vector = [random.random() for _ in range(dimension)]
# Execute the query
query_result = index.query(
vector=query_vector,
include_metadata=True,
include_data=True,
include_vectors=False,
top_k=5,
filter="genre = 'fantasy' and title = 'Lord of the Rings'",
)
# Print the query result
for result in query_result:
print("Score:", result.score)
print("ID:", result.id)
print("Vector:", result.vector)
print("Metadata:", result.metadata)
print("Data:", result.data)
```
----------------------------------------
TITLE: Vector-based Resumable Query Implementation in TypeScript
DESCRIPTION: Example showing how to perform a resumable vector query using a direct vector input. Includes fetching initial results with metadata and vectors, retrieving additional results, and properly closing the query.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/ts/commands/resumable-query.mdx#2025-04-11_snippet_0
LANGUAGE: typescript
CODE:
```
const { result, fetchNext, stop } = await index.resumableQuery({
maxIdle: 3600,
topK: 50,
vector: [0, 1, 2, ..., 383], // 384-dimensional vector
includeMetadata: true,
includeVectors: true,
});
console.log(result);
/*
[
{
id: '6345',
score: 1.00000012,
vector: [0, 1, 2, ..., 383],
metadata: {
sentence: "Upstash is great."
}
},
// ... more results
]
*/
const nextBatch = await fetchNext(5); // Fetch next 5 results
console.log(nextBatch);
await stop(); // Stop the resumable query
```
----------------------------------------
TITLE: Querying Hybrid Index using Reciprocal Rank Fusion in PHP
DESCRIPTION: This PHP code example demonstrates how to query a hybrid index using the Reciprocal Rank Fusion (RRF) algorithm. It creates an Index object and performs a query with both dense and sparse vectors, setting RRF as the fusion algorithm.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/hybridindexes.mdx#2025-04-11_snippet_7
LANGUAGE: php
CODE:
```
use Upstash\Vector\Index;
use Upstash\Vector\VectorQuery;
use Upstash\Vector\SparseVector;
use Upstash\Vector\Enums\FusionAlgorithm;
$index = new Index(
url: 'UPSTASH_VECTOR_REST_URL',
token: 'UPSTASH_VECTOR_REST_TOKEN',
);
$index->query(new VectorQuery(
vector: [0.5, 0.4],
sparseVector: new SparseVector(
indices: [3, 5],
values: [0.3, 0.5],
),
topK: 5,
includeMetadata: true,
fusionAlgorithm: FusionAlgorithm::RECIPROCAL_RANK_FUSION,
));
```
----------------------------------------
TITLE: Querying Vectors using cURL in Upstash Vector Database
DESCRIPTION: Basic cURL command to query vectors in the default namespace. The request includes the vector values, topK parameter to limit results, and includeMetadata flag to return vector metadata.
SOURCE: https://github.com/upstash/docs/blob/main/vector/api/endpoints/query.mdx#2025-04-11_snippet_0
LANGUAGE: sh
CODE:
```
curl $UPSTASH_VECTOR_REST_URL/query \
-X POST \
-H "Authorization: Bearer $UPSTASH_VECTOR_REST_TOKEN" \
-d '{ "vector": [0.1, 0.2], "topK": 2, "includeMetadata": true }'
```
----------------------------------------
TITLE: Performing Semantic Search with Upstash Vector and LangChain
DESCRIPTION: Code to execute a semantic search query against the vector database. This example searches for content related to technology's role in global warming and returns the top 5 most similar document chunks.
SOURCE: https://github.com/upstash/docs/blob/main/vector/tutorials/langchain.mdx#2025-04-11_snippet_5
LANGUAGE: python
CODE:
```
result = store.similarity_search("Technology's role in global warming.", k=5)
print(result)
```
----------------------------------------
TITLE: Batch Querying Multiple Vectors in Python
DESCRIPTION: This snippet demonstrates how to perform batch querying in Upstash Vector to reduce round trips to the server. It creates multiple random query vectors, executes multiple queries with different parameters in a single API call, and prints the results for each query.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/py/example_calls/query.mdx#2025-04-11_snippet_1
LANGUAGE: python
CODE:
```
import random
from upstash_vector import Index
index = Index.from_env()
# Generate a random vector for similarity comparison
dimension = 128 # Adjust based on your index's dimension
query_vectors = [[random.random() for _ in range(dimension)] for _ in range(2)]
# Execute the query
query_results = index.query_many(
queries=[
{
"vector": query_vectors[0],
"include_metadata": True,
"include_data": True,
"include_vectors": False,
"top_k": 5,
"filter": "genre = 'fantasy' and title = 'Lord of the Rings'",
},
{
"vector": query_vectors[1],
"include_metadata": False,
"include_data": False,
"include_vectors": True,
"top_k": 3,
"filter": "genre = 'drama'",
},
]
)
for i, query_result in enumerate(query_results):
print(f"Query-{i} result:")
# Print the query result
for result in query_result:
print("Score:", result.score)
print("ID:", result.id)
print("Vector:", result.vector)
print("Metadata:", result.metadata)
print("Data:", result.data)
```
----------------------------------------
TITLE: Creating and Storing Document Embeddings
DESCRIPTION: Code for creating sample documents, embedding them, and storing in Upstash Vector with batch processing
SOURCE: https://github.com/upstash/docs/blob/main/vector/tutorials/huggingface-embeddings.mdx#2025-04-11_snippet_3
LANGUAGE: python
CODE:
```
# Import the required Document class from LangChain\nfrom langchain.schema import Document\n\n# Sample documents to embed and store as Document objects\ndocuments = [\n Document(page_content="Global warming is causing sea levels to rise."),\n Document(page_content="Artificial intelligence is transforming many industries."),\n Document(page_content="Renewable energy is vital for sustainable development.")\n]\n\n# Embed documents and store in Upstash Vector with batching\nvector_store.add_documents(\n documents=documents,\n batch_size=100, \n embedding_chunk_size=200 \n)\n\nprint("Documents with embeddings have been stored in Upstash Vector.")
```
----------------------------------------
TITLE: Filtering Vectors by Metadata in JavaScript
DESCRIPTION: Example showing how to query vectors with metadata filtering in JavaScript. The filter uses GLOB pattern matching to find vectors with metadata URLs containing 'imgur.com'.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/metadata.mdx#2025-04-11_snippet_12
LANGUAGE: javascript
CODE:
```
import { Index } from "@upstash/vector"
const index = new Index({
url: "UPSTASH_VECTOR_REST_URL",
token: "UPSTASH_VECTOR_REST_TOKEN",
})
await index.query({
vector: [0.9215, 0.3897],
topK: 5,
includeMetadata: true,
filter: "url GLOB '*imgur.com*'",
})
```
----------------------------------------
TITLE: Starting a Resumable Query in JavaScript with Upstash Vector
DESCRIPTION: Initializes a resumable vector similarity search query in JavaScript that returns the first batch of results along with functions to fetch more results or stop the query. The example includes metadata in the results and requests the top 2 most similar vectors.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/resumablequery.mdx#2025-04-11_snippet_1
LANGUAGE: javascript
CODE:
```
import { Index } from "@upstash/vector"
const index = new Index({
url: "UPSTASH_VECTOR_REST_URL",
token: "UPSTASH_VECTOR_REST_TOKEN",
});
const { result, fetchNext, stop } = await index.resumableQuery({
vector: [0.1, 0.2],
topK: 2,
includeMetadata: true,
});
// first batch of the results
for (let r of result) {
console.log(r);
}
```
----------------------------------------
TITLE: Querying Hybrid Index using Distribution-Based Score Fusion in Go
DESCRIPTION: This Go code snippet illustrates how to query a hybrid index using the Distribution-Based Score Fusion (DBSF) algorithm. It initializes an Index and performs a query with both dense and sparse vectors, specifying DBSF as the fusion algorithm.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/hybridindexes.mdx#2025-04-11_snippet_11
LANGUAGE: go
CODE:
```
package main
import (
"github.com/upstash/vector-go"
)
func main() {
index := vector.NewIndex(
"UPSTASH_VECTOR_REST_URL",
"UPSTASH_VECTOR_REST_TOKEN",
)
scores, err := index.Query(vector.Query{
Vector: []float32{0.5, 0.4},
SparseVector: &vector.SparseVector{
Indices: []int32{3, 5},
Values: []float32{0.3, 05},
},
FusionAlgorithm: vector.FusionAlgorithmDBSF,
})
}
```
----------------------------------------
TITLE: Querying with Metadata Filter in Python
DESCRIPTION: Example of how to perform a vector similarity search with metadata filtering using the Upstash Vector Python client. The query includes a vector, filter condition, top-k limit, and metadata inclusion.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/filtering.mdx#2025-04-11_snippet_1
LANGUAGE: python
CODE:
```
from upstash_vector import Index
index = Index(
url="UPSTASH_VECTOR_REST_URL",
token="UPSTASH_VECTOR_REST_TOKEN",
)
index.query(
vector=[0.9215, 0.3897],
filter="population >= 1000000 AND geography.continent = 'Asia'",
top_k=5,
include_metadata=True
)
```
----------------------------------------
TITLE: Querying Vectors with Metadata in Python
DESCRIPTION: Example showing how to query vectors and include their metadata in the response in Python. The query searches for similar vectors and returns the top 5 matches with their metadata.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/metadata.mdx#2025-04-11_snippet_5
LANGUAGE: python
CODE:
```
from upstash_vector import Index
index = Index(
url="UPSTASH_VECTOR_REST_URL",
token="UPSTASH_VECTOR_REST_TOKEN",
)
index.query(
[0.9215, 0.3897],
top_k=5,
include_metadata=True,
)
```
----------------------------------------
TITLE: Document Parsing with LlamaParse
DESCRIPTION: Implementation for parsing a text document using LlamaParse with markdown output format.
SOURCE: https://github.com/upstash/docs/blob/main/vector/tutorials/llamaparse.mdx#2025-04-11_snippet_2
LANGUAGE: python
CODE:
```
from llama_parse import LlamaParse
from llama_index.core import SimpleDirectoryReader
# Initialize the LlamaParse parser with the desired result format
parser = LlamaParse(result_type="markdown") # "markdown" and "text" are available
# Parse the document using the parser
file_extractor = {".txt": parser}
documents = SimpleDirectoryReader(input_files=["./documents/global_warming.txt"], file_extractor=file_extractor).load_data()
```
----------------------------------------
TITLE: Complete Example of Vector Upsert Operation
DESCRIPTION: Full example demonstrating how to use the Upstash Vector SDK to upsert a random vector with metadata into the database. This includes initializing the client, creating a vector, and performing the upsert operation.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/py/gettingstarted.mdx#2025-04-11_snippet_3
LANGUAGE: python
CODE:
```
import random
from upstash_vector import Index
# Initialize the index client using environment variables
index = 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)
])
```
----------------------------------------
TITLE: Querying Upstash Vector Index using PHP
DESCRIPTION: Code for performing a similarity search in an Upstash Vector Index using the PHP SDK. It demonstrates how to query the index with a vector, limit results, and include metadata in the response.
SOURCE: https://github.com/upstash/docs/blob/main/vector/overall/getstarted.mdx#2025-04-11_snippet_8
LANGUAGE: php
CODE:
```
use Upstash\Vector\Index;
use Upstash\Vector\VectorQuery;
$index = new Index(
url: '',
token: '',
);
$index->query(new VectorQuery(
vector: [0.6, 0.8],
topK: 3,
includeMetadata: true,
));
```
----------------------------------------
TITLE: Fetching All Results Using Resumable Query in Python for Upstash Vector Database
DESCRIPTION: This example shows how to efficiently fetch all results using a resumable query. It demonstrates a pattern for retrieving large result sets without loading everything into memory at once.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/py/example_calls/resumable-query.mdx#2025-04-11_snippet_4
LANGUAGE: python
CODE:
```
query = index.resumable_query(
vector=[0.1, 0.2],
top_k=2,
include_metadata=True
)
results = query.start()
while True:
next_batch = query.fetch_next(2)
if not next_batch:
break
results.extend(next_batch)
query.stop()
```
----------------------------------------
TITLE: Querying with Metadata Filtering in PHP using Upstash Vector SDK
DESCRIPTION: This example demonstrates how to apply metadata filters when querying vectors using the Upstash Vector PHP SDK. It filters results based on country and continent metadata.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/php/commands/query.mdx#2025-04-11_snippet_4
LANGUAGE: php
CODE:
```
use Upstash\Vector\Index;
use Upstash\Vector\VectorQuery;
$index = new Index(
url: "",
token: "",
);
$results = $index->query(new VectorQuery(
vector: [0.1, 0.2, ...],
topK: 15,
filter: "country = 'PT' AND continent = 'EU'"
));
```
----------------------------------------
TITLE: Querying with Metadata Filter in JavaScript
DESCRIPTION: Example of how to perform a vector similarity search with metadata filtering using the Upstash Vector JavaScript client. The query includes a vector, filter condition, top-k limit, and metadata inclusion.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/filtering.mdx#2025-04-11_snippet_2
LANGUAGE: javascript
CODE:
```
import { Index } from "@upstash/vector"
const index = new Index({
url: "UPSTASH_VECTOR_REST_URL",
token: "UPSTASH_VECTOR_REST_TOKEN",
})
await index.query({
vector: [0.9215, 0.3897],
filter: "population >= 1000000 AND geography.continent = 'Asia'",
topK: 5,
includeMetadata: true,
});
```
----------------------------------------
TITLE: Querying Upstash Vector Index in JavaScript
DESCRIPTION: This snippet demonstrates how to initialize an Upstash Vector index and perform dense and sparse queries using JavaScript. It uses the @upstash/vector package and shows how to set up the index with REST URL and token, then execute queries with different modes.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/hybridindexes.mdx#2025-04-11_snippet_20
LANGUAGE: javascript
CODE:
```
import { Index, QueryMode } from "@upstash/vector"
const index = new Index({
url: "UPSTASH_VECTOR_REST_URL",
token: "UPSTASH_VECTOR_REST_TOKEN",
})
const denseResults = await index.query({
data: "Upstash Vector",
queryMode: QueryMode.DENSE,
})
const sparseResults = await index.query({
data: "Upstash Vector",
queryMode: QueryMode.SPARSE,
})
// Rerank dense and sparse results as you like here
```
----------------------------------------
TITLE: Implementing Custom Reranking for Hybrid Index in JavaScript
DESCRIPTION: This JavaScript code example shows how to implement custom reranking for a hybrid index. It performs separate queries for dense and sparse components, allowing for custom reranking of the results.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/hybridindexes.mdx#2025-04-11_snippet_15
LANGUAGE: javascript
CODE:
```
import { Index } from "@upstash/vector"
const index = new Index({
url: "UPSTASH_VECTOR_REST_URL",
token: "UPSTASH_VECTOR_REST_TOKEN",
})
const denseResults = await index.query(
{
vector: [0.5, 0.4],
topK: 3,
},
)
const sparseResults = await index.query(
{
sparseVector: {
indices: [2, 3],
values: [0.13, 0.87],
},
topK: 3,
},
)
// Rerank dense and sparse results as you like here
```
----------------------------------------
TITLE: Resuming a Resumable Query in Go with Upstash Vector
DESCRIPTION: Fetches additional similar vectors from a previously started resumable query in Go using the query handle. The example demonstrates fetching multiple additional batches of results, first requesting 3 more vectors, then 5 more.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/resumablequery.mdx#2025-04-11_snippet_6
LANGUAGE: go
CODE:
```
// next batch of the results
scores, err = handle.Next(vector.ResumableQueryNext{
AdditionalK: 3,
})
if err != nil {
log.Fatal(err)
}
for _, score := range scores {
fmt.Printf("%+v\n", score)
}
// it is possible to call Next more than once
scores, err = handle.Next(vector.ResumableQueryNext{
AdditionalK: 5,
})
if err != nil {
log.Fatal(err)
}
for _, score := range scores {
fmt.Printf("%+v\n", score)
}
```
----------------------------------------
TITLE: Inserting Data into Upstash Vector Index using JavaScript
DESCRIPTION: Code for upserting vector data into an Upstash Vector Index using the JavaScript SDK. It demonstrates how to create an Index instance and insert a vector with ID, embedding values, and metadata.
SOURCE: https://github.com/upstash/docs/blob/main/vector/overall/getstarted.mdx#2025-04-11_snippet_1
LANGUAGE: javascript
CODE:
```
import { Index } from "@upstash/vector";
const index = new Index({
url: "UPSTASH_VECTOR_REST_URL",
token: "UPSTASH_VECTOR_REST_TOKEN",
})
await index.upsert({ id: "1", vector: [0.6, 0.8], metadata: {field: "value"} })
```
----------------------------------------
TITLE: Querying Hybrid Index using Distribution-Based Score Fusion in Python
DESCRIPTION: This Python code snippet demonstrates how to query a hybrid index using the Distribution-Based Score Fusion (DBSF) algorithm. It initializes an Index object and performs a query with both dense and sparse vectors, specifying DBSF as the fusion algorithm.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/hybridindexes.mdx#2025-04-11_snippet_9
LANGUAGE: python
CODE:
```
from upstash_vector import Index
from upstash_vector.types import FusionAlgorithm, SparseVector
index = Index(
url="UPSTASH_VECTOR_REST_URL",
token="UPSTASH_VECTOR_REST_TOKEN",
)
index.query(
vector=[0.5, 0.4],
sparse_vector=SparseVector([3, 5], [0.3, 0.5]),
fusion_algorithm=FusionAlgorithm.DBSF,
)
```
----------------------------------------
TITLE: Querying Dense Index in PHP using Upstash Vector SDK
DESCRIPTION: This snippet demonstrates how to query a dense vector index using the Upstash Vector PHP SDK. It includes options for limiting results, including metadata, vectors, and data in the response, and applying filters.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/php/commands/query.mdx#2025-04-11_snippet_0
LANGUAGE: php
CODE:
```
use Upstash\Vector\Index;
use Upstash\Vector\VectorQuery;
$index = new Index(
url: "",
token: "",
);
$results = $index->query(new VectorQuery(
vector: [0.1, 0.2, ...], // "..." represents the dimension size of your vector index.
topK: 15, // topK is the limit number of records we want to be returned.
includeMetadata: true, // (optional) if true the query results will contain metadata.
includeVectors: true, // (optional) if true the query results will contain the indexed vectors.
includeData: true, // (optional) if true the query results will contain the string data.
filter: '', // (optional) if set, the query results will be filtered by the given filter.
));
```
----------------------------------------
TITLE: Filtering Vectors by Metadata using curl
DESCRIPTION: Example showing how to query vectors with metadata filtering using curl. The request includes a filter to match vectors with metadata URLs containing 'imgur.com'.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/metadata.mdx#2025-04-11_snippet_15
LANGUAGE: shell
CODE:
```
curl $UPSTASH_VECTOR_REST_URL/query \
-H "Authorization: Bearer $UPSTASH_VECTOR_REST_TOKEN" \
-d '{
"vector":[0.9215,0.3897],
"topK" : 5,
"includeMetadata": true,
"filter": "url GLOB \"*imgur.com*\""
}'
```
----------------------------------------
TITLE: Querying Hybrid Index using Reciprocal Rank Fusion with cURL
DESCRIPTION: This cURL command shows how to query a hybrid index using the Reciprocal Rank Fusion (RRF) algorithm via the REST API. It sends a POST request with both dense and sparse vectors, specifying RRF as the fusion algorithm.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/hybridindexes.mdx#2025-04-11_snippet_8
LANGUAGE: shell
CODE:
```
curl $UPSTASH_VECTOR_REST_URL/query \
-H "Authorization: Bearer $UPSTASH_VECTOR_REST_TOKEN" \
-d '{"vector": [0.5, 0.4], "sparseVector": {"indices": [3, 5], "values": [0.3, 0.5]}, "fusionAlgorithm": "RRF"}'
```
----------------------------------------
TITLE: Querying Hybrid Indexes with Text
DESCRIPTION: Examples showing how to query hybrid indexes using text input that gets automatically converted to vectors using Upstash-hosted embedding models.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/hybridindexes.mdx#2025-04-11_snippet_3
LANGUAGE: python
CODE:
```
from upstash_vector import Index
index = Index(
url="UPSTASH_VECTOR_REST_URL",
token="UPSTASH_VECTOR_REST_TOKEN",
)
index.query(
data="Upstash Vector",
top_k=5,
)
```
LANGUAGE: javascript
CODE:
```
import { Index } from "@upstash/vector"
const index = new Index({
url: "UPSTASH_VECTOR_REST_URL",
token: "UPSTASH_VECTOR_REST_TOKEN",
})
await index.query(
{
data: "Upstash Vector",
topK: 1,
},
)
```
----------------------------------------
TITLE: Filtering Vectors by Metadata in Go
DESCRIPTION: Example showing how to query vectors with metadata filtering in Go. The query uses a GLOB filter to match only vectors with metadata URLs containing 'imgur.com'.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/metadata.mdx#2025-04-11_snippet_13
LANGUAGE: go
CODE:
```
package main
import (
"github.com/upstash/vector-go"
)
func main() {
index := vector.NewIndex("UPSTASH_VECTOR_REST_URL", "UPSTASH_VECTOR_REST_TOKEN")
index.Query(vector.Query{
Vector: []float32{0.9215, 0.3897},
TopK: 5,
IncludeMetadata: true,
Filter: "url GLOB '*imgur.com*'",
})
}
```
----------------------------------------
TITLE: Querying Vectors with Data Inclusion
DESCRIPTION: Shows how to query vectors while including their associated data in the results. The example demonstrates querying by text and processing the returned data fields.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/metadata.mdx#2025-04-11_snippet_24
LANGUAGE: python
CODE:
```
from upstash_vector import Index
index = Index(
url="UPSTASH_VECTOR_REST_URL",
token="UPSTASH_VECTOR_REST_TOKEN",
)
result = index.query(
data="What is Upstash?",
include_data=True,
)
for res in result:
print(f"{res.id}: {res.data}")
```
LANGUAGE: javascript
CODE:
```
import { Index } from "@upstash/vector"
const index = new Index({
url: "UPSTASH_VECTOR_REST_URL",
token: "UPSTASH_VECTOR_REST_TOKEN",
})
const result = await index.query({
data: "What is Upstash?",
includeData: true,
topK: 3
})
for (const vector of result) {
console.log(`${vector.id}: ${vector.data}`)
}
```
LANGUAGE: php
CODE:
```
use Upstash\Vector\Index;
use Upstash\Vector\DataQuery;
$index = new Index(
url: 'UPSTASH_VECTOR_REST_URL',
token: 'UPSTASH_VECTOR_REST_TOKEN',
);
$results = $index->queryData(new DataQuery(
data: 'Upstash is a serverless data platform.',
topK: 3
includeData: true,
));
foreach ($results as $result) {
print_r($result->toArray());
}
```
LANGUAGE: shell
CODE:
```
curl $UPSTASH_VECTOR_REST_URL/query-data \
-H "Authorization: Bearer $UPSTASH_VECTOR_REST_TOKEN" \
-d '{
"data": "What is Upstash?",
"includeData": true,
}'
```
----------------------------------------
TITLE: Performing Vector-Based Similarity Search
DESCRIPTION: Implementation of similarity search using direct vector input
SOURCE: https://github.com/upstash/docs/blob/main/vector/tutorials/huggingface-embeddings.mdx#2025-04-11_snippet_5
LANGUAGE: python
CODE:
```
# Querying Vectors using a vector directly\nresult_vector_query = vector_store.similarity_search_by_vector(\n embedding=query_embedding,\n k=5\n)\n\nprint("Results for vector-based similarity search:")\nfor res in result_vector_query:\n print(res.page_content)
```
----------------------------------------
TITLE: Querying Hybrid Index using Distribution-Based Score Fusion in JavaScript
DESCRIPTION: This JavaScript code example shows how to query a hybrid index using the Distribution-Based Score Fusion (DBSF) algorithm. It creates an Index instance and performs a query with both dense and sparse vectors, setting DBSF as the fusion algorithm.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/hybridindexes.mdx#2025-04-11_snippet_10
LANGUAGE: javascript
CODE:
```
import { FusionAlgorithm, Index } from "@upstash/vector";
const index = new Index({
url: "UPSTASH_VECTOR_REST_URL",
token: "UPSTASH_VECTOR_REST_TOKEN",
});
await index.query({
vector: [0.5, 0.4],
sparseVector: {
indices: [2, 3],
values: [0.13, 0.87],
},
fusionAlgorithm: FusionAlgorithm.DBSF,
topK: 3,
});
```
----------------------------------------
TITLE: Starting a Resumable Query in Python with Upstash Vector
DESCRIPTION: Initializes a resumable vector similarity search query in Python that returns the first batch of results along with a handle for fetching more results later. The example includes metadata in the results and requests the top 2 most similar vectors.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/resumablequery.mdx#2025-04-11_snippet_0
LANGUAGE: python
CODE:
```
from upstash_vector import Index
index = Index(
url="UPSTASH_VECTOR_REST_URL",
token="UPSTASH_VECTOR_REST_TOKEN",
)
result, handle = index.resumable_query(
vector=[0.1, 0.2],
top_k=2,
include_metadata=True,
)
# first batch of the results
for r in result:
print(r)
```
----------------------------------------
TITLE: Querying Vectors with Metadata in JavaScript
DESCRIPTION: Example showing how to query vectors and include their metadata in the response in JavaScript. The query returns the top 5 vectors most similar to the provided vector.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/metadata.mdx#2025-04-11_snippet_6
LANGUAGE: javascript
CODE:
```
import { Index } from "@upstash/vector"
const index = new Index({
url: "UPSTASH_VECTOR_REST_URL",
token: "UPSTASH_VECTOR_REST_TOKEN",
})
await index.query({
vector: [0.9215, 0.3897],
topK: 5,
includeMetadata: true,
})
```
----------------------------------------
TITLE: Upserting Text Data with Embedding Models in JavaScript
DESCRIPTION: Shows how to upsert raw text data into Upstash Vector using JavaScript. The text will be automatically converted to vector embeddings by the selected model.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/embeddingmodels.mdx#2025-04-11_snippet_1
LANGUAGE: javascript
CODE:
```
import { Index } from "@upstash/vector"
const index = new Index({
url: "UPSTASH_VECTOR_REST_URL",
token: "UPSTASH_VECTOR_REST_TOKEN",
})
await index.upsert({
id: "id-0",
data: "Upstash is a serverless data platform.",
metadata: {
field: "value",
},
})
```
----------------------------------------
TITLE: Filtering Vectors by Metadata in Python
DESCRIPTION: Example showing how to query vectors with metadata filtering in Python. The query includes a GLOB filter to match only vectors with an Imgur URL in their metadata.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/metadata.mdx#2025-04-11_snippet_11
LANGUAGE: python
CODE:
```
from upstash_vector import Index
index = Index(
url="UPSTASH_VECTOR_REST_URL",
token="UPSTASH_VECTOR_REST_TOKEN",
)
index.query(
[0.9215, 0.3897],
top_k=5,
include_metadata=True,
filter="url GLOB '*imgur.com*'",
)
```
----------------------------------------
TITLE: Using OpenAI Embeddings with Upstash Vector Store
DESCRIPTION: Example of configuring Upstash Vector Store to use OpenAI's embeddings instead of the default Upstash-generated embeddings. This gives more control over the embedding model being used.
SOURCE: https://github.com/upstash/docs/blob/main/vector/tutorials/langchain.mdx#2025-04-11_snippet_7
LANGUAGE: python
CODE:
```
from langchain_openai import OpenAIEmbeddings
store = UpstashVectorStore(embedding=OpenAIEmbeddings())
```
----------------------------------------
TITLE: Querying Text Data with Upstash Vector in Python
DESCRIPTION: This snippet demonstrates how to query text data in an Upstash Vector index using Python. It creates an Index object and uses the query method with text data to search for similar vectors.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/sparseindexes.mdx#2025-04-11_snippet_16
LANGUAGE: python
CODE:
```
from upstash_vector import Index
index = Index(
url="UPSTASH_VECTOR_REST_URL",
token="UPSTASH_VECTOR_REST_TOKEN",
)
index.query(
data="Upstash Vector",
top_k=5,
)
```
----------------------------------------
TITLE: Starting and Fetching Results from a Resumable Query in Python
DESCRIPTION: This snippet shows how to start a resumable query, fetch initial results, and then retrieve additional results. It also demonstrates how to stop the query when finished to release resources.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/py/example_calls/resumable-query.mdx#2025-04-11_snippet_1
LANGUAGE: python
CODE:
```
initial_results = query.start()
next_results = query.fetch_next(number_of_results)
stop_result = query.stop()
assert stop_result == 'Success'
```
----------------------------------------
TITLE: Weighting Query Values with IDF in Upstash Vector (Python)
DESCRIPTION: This snippet shows how to use Inverse Document Frequency (IDF) weighting when querying text data in Upstash Vector using Python. It demonstrates the use of the WeightingStrategy.IDF option.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/sparseindexes.mdx#2025-04-11_snippet_21
LANGUAGE: python
CODE:
```
from upstash_vector import Index
from upstash_vector.types import WeightingStrategy
index = Index(
url="UPSTASH_VECTOR_REST_URL",
token="UPSTASH_VECTOR_REST_TOKEN",
)
index.query(
data="Upstash Vector",
top_k=5,
weighting_strategy=WeightingStrategy.IDF,
)
```
----------------------------------------
TITLE: Querying Hybrid Index using Reciprocal Rank Fusion in Python
DESCRIPTION: This snippet demonstrates how to query a hybrid index using the Reciprocal Rank Fusion (RRF) algorithm in Python. It initializes an Index object and performs a query with both dense and sparse vectors, specifying RRF as the fusion algorithm.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/hybridindexes.mdx#2025-04-11_snippet_4
LANGUAGE: python
CODE:
```
from upstash_vector import Index
from upstash_vector.types import FusionAlgorithm, SparseVector
index = Index(
url="UPSTASH_VECTOR_REST_URL",
token="UPSTASH_VECTOR_REST_TOKEN",
)
index.query(
vector=[0.5, 0.4],
sparse_vector=SparseVector([3, 5], [0.3, 0.5]),
fusion_algorithm=FusionAlgorithm.RRF,
)
```
----------------------------------------
TITLE: Resuming a Resumable Query in JavaScript with Upstash Vector
DESCRIPTION: Fetches additional similar vectors from a previously started resumable query in JavaScript using the fetchNext function. The example demonstrates fetching multiple additional batches of results, first requesting 3 more vectors, then 3 more.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/resumablequery.mdx#2025-04-11_snippet_5
LANGUAGE: javascript
CODE:
```
// next batch of the results
let nextResult = await fetchNext(3);
for (let r of nextResult) {
console.log(r);
}
// it is possible to call fetch_next more than once
nextResult = await fetchNext(3);
for (let r of nextResult) {
console.log(r);
}
```
----------------------------------------
TITLE: Batch Querying Vectors using cURL
DESCRIPTION: cURL command for sending a batch query request to Upstash Vector Database. The request contains an array of query objects, each with their own parameters like vector values, topK, and includeMetadata settings.
SOURCE: https://github.com/upstash/docs/blob/main/vector/api/endpoints/query.mdx#2025-04-11_snippet_2
LANGUAGE: sh
CODE:
```
curl "$UPSTASH_VECTOR_REST_URL/query" \
-X POST \
-H "Authorization: Bearer $UPSTASH_VECTOR_REST_TOKEN" \
-d '[
{
"vector": [0.1, 0.2],
"topK": 2,
"includeMetadata": true
},
{
"vector": [0.2, 0.3],
"topK": 3
}
]'
```
----------------------------------------
TITLE: Scanning Complete Index with Pagination
DESCRIPTION: Demonstrates how to scan the entire index using cursor-based pagination with a while loop, processing results in batches.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/py/example_calls/range.mdx#2025-04-11_snippet_2
LANGUAGE: python
CODE:
```
res = index.range(cursor="", limit=5)
print(res.vectors)
while res.next_cursor != "":
res = index.range(cursor=res.next_cursor, limit=10)
print(res.vectors)
```
----------------------------------------
TITLE: Upserting Dense and Sparse Vectors
DESCRIPTION: Examples of upserting both dense and sparse vectors into Upstash Vector indexes using different programming languages. Shows how to create and insert vector combinations with proper formatting and structure.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/hybridindexes.mdx#2025-04-11_snippet_0
LANGUAGE: python
CODE:
```
from upstash_vector import Index, Vector
from upstash_vector.types import SparseVector
index = Index(
url="UPSTASH_VECTOR_REST_URL",
token="UPSTASH_VECTOR_REST_TOKEN",
)
index.upsert(
vectors=[
Vector(id="id-0", vector=[0.1, 0.5], sparse_vector=SparseVector([1, 2], [0.1, 0.2])),
Vector(id="id-1", vector=[0.3, 0.7], sparse_vector=SparseVector([123, 44232], [0.5, 0.4])),
]
)
```
LANGUAGE: javascript
CODE:
```
import { Index } from "@upstash/vector"
const index = new Index({
url: "UPSTASH_VECTOR_REST_URL",
token: "UPSTASH_VECTOR_REST_TOKEN",
})
await index.upsert([{
id: 'id-0',
vector: [0.1, 0.5],
sparseVector: {
indices: [2, 3],
values: [0.13, 0.87],
},
}])
```
----------------------------------------
TITLE: Querying Vectors with Metadata in Go
DESCRIPTION: Example showing how to query vectors and include their metadata in the response in Go. The query retrieves the top 5 vectors most similar to the input vector along with their metadata.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/metadata.mdx#2025-04-11_snippet_7
LANGUAGE: go
CODE:
```
package main
import (
"github.com/upstash/vector-go"
)
func main() {
index := vector.NewIndex("UPSTASH_VECTOR_REST_URL", "UPSTASH_VECTOR_REST_TOKEN")
index.Query(vector.Query{
Vector: []float32{0.9215, 0.3897},
TopK: 5,
IncludeMetadata: true,
})
}
```
----------------------------------------
TITLE: Resuming a Resumable Query in Python with Upstash Vector
DESCRIPTION: Fetches additional similar vectors from a previously started resumable query in Python using the query handle. The example demonstrates fetching multiple additional batches of results, first requesting 3 more vectors, then 5 more.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/resumablequery.mdx#2025-04-11_snippet_4
LANGUAGE: python
CODE:
```
# next batch of the results
next_result = handle.fetch_next(
additional_k=3,
)
for r in next_result:
print(r)
# it is possible to call fetch_next more than once
next_result = handle.fetch_next(
additional_k=5,
)
for r in next_result:
print(r)
```
----------------------------------------
TITLE: Weighting Query Values with IDF in Upstash Vector (Go)
DESCRIPTION: This snippet shows how to use Inverse Document Frequency (IDF) weighting when querying text data in Upstash Vector using Go. It demonstrates the use of the WeightingStrategyIDF option.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/sparseindexes.mdx#2025-04-11_snippet_23
LANGUAGE: go
CODE:
```
package main
import (
"github.com/upstash/vector-go"
)
func main() {
index := vector.NewIndex(
"UPSTASH_VECTOR_REST_URL",
"UPSTASH_VECTOR_REST_TOKEN",
)
scores, err := index.QueryData(vector.QueryData{
Data: "Upstash Vector",
TopK: 5,
WeightingStrategy: vector.WeightingStrategyIDF,
})
}
```
----------------------------------------
TITLE: Simple Vector Upsert in PHP
DESCRIPTION: Demonstrates how to upsert a single vector into an Upstash Vector index using the PHP SDK. Creates a new Index instance and uses the upsert() method with a VectorUpsert object containing an ID and vector data.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/php/commands/upsert-vectors.mdx#2025-04-11_snippet_0
LANGUAGE: php
CODE:
```
use Upstash\Vector\Index;
use Upstash\Vector\VectorUpsert;
use function Upstash\Vector\createRandomVector;
$index = new Index(
url: "",
token: "",
);
$index->upsert(new VectorUpsert(
id: '1',
vector: createRandomVector(dimensions: 1536)
));
```
----------------------------------------
TITLE: Asynchronous Resumable Query Operations in Python for Upstash Vector Database
DESCRIPTION: This snippet illustrates how to perform asynchronous operations with resumable queries using the AsyncIndex class. It covers creating, starting, fetching results, and stopping the query asynchronously.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/py/example_calls/resumable-query.mdx#2025-04-11_snippet_2
LANGUAGE: python
CODE:
```
query = await async_index.resumable_query(
vector=[0.1, 0.2],
top_k=2,
include_metadata=True,
include_vectors=True,
namespace='your_namespace'
)
initial_results = await query.async_start()
next_results = await query.async_fetch_next(number_of_results)
stop_result = await query.async_stop()
assert stop_result == 'Success'
```
----------------------------------------
TITLE: Typed Metadata Resumable Query Implementation in TypeScript
DESCRIPTION: Example showing resumable query implementation with strongly typed metadata filtering. Demonstrates type-safe metadata handling and filtering based on specific metadata fields.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/ts/commands/resumable-query.mdx#2025-04-11_snippet_2
LANGUAGE: typescript
CODE:
```
type Metadata = {
title: string,
genre: 'sci-fi' | 'fantasy' | 'horror' | 'action'
}
const { result, fetchNext, stop } = await index.resumableQuery({
vector: [
... // query embedding
],
includeMetadata: true,
topK: 1,
filter: "genre = 'fantasy' and title = 'Lord of the Rings'",
maxIdle: 3600,
})
if (result[0].metadata) {
// Since we passed the Metadata type parameter above,
// we can interact with metadata fields without having to
// do any typecasting.
const { title, genre } = result[0].metadata;
console.log(`The best match in fantasy was ${title}`)
}
await stop();
```
----------------------------------------
TITLE: Querying Upstash Vector Index using JavaScript
DESCRIPTION: Code for performing a similarity search in an Upstash Vector Index using the JavaScript SDK. It demonstrates how to query the index with a vector, limit results, and include metadata in the response.
SOURCE: https://github.com/upstash/docs/blob/main/vector/overall/getstarted.mdx#2025-04-11_snippet_6
LANGUAGE: javascript
CODE:
```
import { Index } from "@upstash/vector";
const index = new Index({
url: "UPSTASH_VECTOR_REST_URL",
token: "UPSTASH_VECTOR_REST_TOKEN",
})
await index.query({ vector: [0.6, 0.8], topK: 3, includeMetadata: true })
```
----------------------------------------
TITLE: Batch Upserting Multiple Data Items in PHP
DESCRIPTION: This snippet demonstrates how to upsert multiple data items at once using the Upstash Vector SDK in PHP. It initializes an Index object and uses the upsertDataMany() method to insert or update multiple data items with automatic vector generation.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/php/commands/upsert-data.mdx#2025-04-11_snippet_2
LANGUAGE: php
CODE:
```
use Upstash\Vector\Index;
use Upstash\Vector\DataUpsert;
$index = new Index(
url: "",
token: "",
);
$index->upsertDataMany([
new DataUpsert(id: '1', data: 'The capital of Japan is Tokyo'),
new DataUpsert(id: '2', data: 'The capital of France is Paris'),
new DataUpsert(id: '3', data: 'The capital of Germany is Berlin'),
]);
```
----------------------------------------
TITLE: Querying Sparse Vectors with Upstash Vector in PHP
DESCRIPTION: This snippet demonstrates how to query sparse vectors in an Upstash Vector index using PHP. It creates an Index object and uses the query method with a SparseVector to search for similar vectors.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/sparseindexes.mdx#2025-04-11_snippet_14
LANGUAGE: php
CODE:
```
use Upstash\Vector\Index;
use Upstash\Vector\VectorQuery;
use Upstash\Vector\SparseVector;
$index = new Index(
url: 'UPSTASH_VECTOR_REST_URL',
token: 'UPSTASH_VECTOR_REST_TOKEN',
);
$index->query(new VectorQuery(
sparseVector: new SparseVector(
indices: [3, 5],
values: [0.3, 0.5],
),
topK: 5,
includeMetadata: true,
));
```
----------------------------------------
TITLE: Upserting and Querying Upstash Vector Index with Typed Metadata
DESCRIPTION: TypeScript code showing how to upsert data and query an Upstash Vector index with typed metadata for better type checking.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/ts/overview-backup.mdx#2025-04-11_snippet_5
LANGUAGE: typescript
CODE:
```
type Metadata = {
title: string,
genre: 'sci-fi' | 'fantasy' | 'horror' | 'action'
}
await index.upsert([{
id: '1234',
vector: [
.... // embedding values
],
metadata: {
title: 'Lord of The Rings',
genre: 'drama',
category: 'classic'
}
}])
const results = await index.query({
vector: [
... // query embedding
],
includeVectors: true,
topK: 1,
})
if (results[0].metadata) {
// Since we passed the Metadata type parameter above,
// we can interact with metadata fields without having to
// do any typecasting.
const { title, genre, category } = results[0].metadata;
console.log(`The best match in fantasy was ${title}`)
}
```
----------------------------------------
TITLE: Weighting Query Values with IDF in Upstash Vector (PHP)
DESCRIPTION: This snippet demonstrates how to use Inverse Document Frequency (IDF) weighting when querying text data in Upstash Vector using PHP. It shows the use of the WeightingStrategy::INVERSE_DOCUMENT_FREQUENCY option.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/sparseindexes.mdx#2025-04-11_snippet_24
LANGUAGE: php
CODE:
```
use Upstash\Vector\Index;
use Upstash\Vector\DataQuery;
use Upstash\Vector\Enums\WeightingStrategy;
$index = new Index(
url: 'UPSTASH_VECTOR_REST_URL',
token: 'UPSTASH_VECTOR_REST_TOKEN',
);
$index->queryData(new DataQuery(
data: 'Upstash Vector',
topK: 5,
weightingStrategy: WeightingStrategy::INVERSE_DOCUMENT_FREQUENCY,
));
```
----------------------------------------
TITLE: Batch Upserting Multiple Data Items with Namespace in PHP
DESCRIPTION: This snippet shows how to upsert multiple data items at once using a namespace in Upstash Vector. It creates an Index object, uses the namespace() method, and then calls upsertDataMany() to insert or update multiple data items within a specific namespace.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/php/commands/upsert-data.mdx#2025-04-11_snippet_3
LANGUAGE: php
CODE:
```
use Upstash\Vector\Index;
use Upstash\Vector\DataUpsert;
$index = new Index(
url: "",
token: "",
);
$index->namespace('my-namespace')->upsertDataMany([
new DataUpsert(id: '1', data: 'The capital of Japan is Tokyo'),
new DataUpsert(id: '2', data: 'The capital of France is Paris'),
new DataUpsert(id: '3', data: 'The capital of Germany is Berlin'),
]);
```
----------------------------------------
TITLE: Upserting Sparse Vectors in Python
DESCRIPTION: Demonstrates how to upsert sparse vectors into Upstash Vector indexes using the Python SDK.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/sparseindexes.mdx#2025-04-11_snippet_1
LANGUAGE: python
CODE:
```
from upstash_vector import Index, Vector
from upstash_vector.types import SparseVector
index = Index(
url="UPSTASH_VECTOR_REST_URL",
token="UPSTASH_VECTOR_REST_TOKEN",
)
index.upsert(
vectors=[
Vector(id="id-0", sparse_vector=SparseVector([1, 2], [0.1, 0.2])),
Vector(id="id-1", sparse_vector=SparseVector([123, 44232], [0.5, 0.4])),
]
)
```
----------------------------------------
TITLE: Creating a Resumable Query in Python for Upstash Vector Database
DESCRIPTION: This snippet demonstrates how to create a resumable query using the Index class. It includes various parameters for customizing the query, such as vector input, result count, and metadata inclusion.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/py/example_calls/resumable-query.mdx#2025-04-11_snippet_0
LANGUAGE: python
CODE:
```
query = index.resumable_query(
vector=[0.1, 0.2], # or use 'data' parameter for text-based queries
top_k=2,
include_metadata=True,
include_vectors=True,
namespace="your_namespace"
)
```
----------------------------------------
TITLE: Fetching Vectors by ID Prefix in Upstash Vector with TypeScript
DESCRIPTION: Example of using the prefix parameter to fetch all vectors whose IDs start with a specified prefix. This returns all matching vectors in the result array.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/ts/commands/fetch.mdx#2025-04-11_snippet_2
LANGUAGE: typescript
CODE:
```
await index.fetch({ prefix: "test-" });
// [{ id: "test-1" }, { id: "test-2" }, { id: "test-3" }]
```
----------------------------------------
TITLE: Querying with Embedding Models in PHP using Upstash Vector SDK
DESCRIPTION: This snippet shows how to query an index configured with an embedding model using a simple string input. The SDK automatically converts the string into vector embeddings.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/php/commands/query.mdx#2025-04-11_snippet_3
LANGUAGE: php
CODE:
```
use Upstash\Vector\Index;
use Upstash\Vector\DataQuery;
$index = new Index(
url: "",
token: "",
);
$results = $index->queryData(new DataQuery(
data: 'What is the capital of France?',
topK: 1, // to only return 1 result.
includeData: true,
));
```
----------------------------------------
TITLE: Querying Text Data with Embedding Models using cURL
DESCRIPTION: Shows how to query Upstash Vector with raw text using cURL requests. The query text will be automatically converted to a vector embedding by the selected model for similarity search.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/embeddingmodels.mdx#2025-04-11_snippet_9
LANGUAGE: shell
CODE:
```
curl $UPSTASH_VECTOR_REST_URL/query-data \
-H "Authorization: Bearer $UPSTASH_VECTOR_REST_TOKEN" \
-d '{"data": "What is Upstash?", "topK": 1, "includeMetadata": "true"}'
```
----------------------------------------
TITLE: Querying Text Data with Embedding Models in PHP
DESCRIPTION: Shows how to query Upstash Vector with raw text in PHP. The query text will be automatically converted to a vector embedding by the selected model for similarity search.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/embeddingmodels.mdx#2025-04-11_snippet_8
LANGUAGE: php
CODE:
```
use Upstash\Vector\Index;
use Upstash\Vector\DataQuery;
$index = new Index(
url: 'UPSTASH_VECTOR_REST_URL',
token: 'UPSTASH_VECTOR_REST_TOKEN',
);
$index->queryData(new DataQuery(
data: 'What is Upstash?',
topK: 1,
includeMetadata: true,
));
```
----------------------------------------
TITLE: Upserting Sparse Vectors in JavaScript
DESCRIPTION: Shows how to upsert sparse vectors using the JavaScript SDK for Upstash Vector.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/sparseindexes.mdx#2025-04-11_snippet_2
LANGUAGE: javascript
CODE:
```
import { Index } from "@upstash/vector"
const index = new Index({
url: "UPSTASH_VECTOR_REST_URL",
token: "UPSTASH_VECTOR_REST_TOKEN",
})
await index.upsert([{
id: 'id-0',
sparseVector: {
indices: [2, 3],
values: [0.13, 0.87],
},
}])
```
----------------------------------------
TITLE: Retrieving Vectors with Basic Range Query in TypeScript
DESCRIPTION: This snippet demonstrates a basic usage of the range method to retrieve vectors with pagination. It includes metadata in the response and specifies a namespace.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/ts/commands/range.mdx#2025-04-11_snippet_0
LANGUAGE: typescript
CODE:
```
const responseRange = await index.range(
{
cursor: 0,
limit: 2,
includeMetadata: true,
},
{ namespace: "my-namespace" }
);
/*
{
nextCursor: '2',
vectors: [
{
id: '0',
metadata: {
keyword: "Vector"
}
},
{
id: '19',
metadata: {
keyword: "Redis"
}
}
]
}
*/
```
----------------------------------------
TITLE: Querying Hybrid Index using Reciprocal Rank Fusion in Go
DESCRIPTION: This Go code snippet illustrates how to query a hybrid index using the Reciprocal Rank Fusion (RRF) algorithm. It initializes an Index and performs a query with both dense and sparse vectors, specifying RRF as the fusion algorithm.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/hybridindexes.mdx#2025-04-11_snippet_6
LANGUAGE: go
CODE:
```
package main
import (
"github.com/upstash/vector-go"
)
func main() {
index := vector.NewIndex(
"UPSTASH_VECTOR_REST_URL",
"UPSTASH_VECTOR_REST_TOKEN",
)
scores, err := index.Query(vector.Query{
Vector: []float32{0.5, 0.4},
SparseVector: &vector.SparseVector{
Indices: []int32{3, 5},
Values: []float32{0.3, 05},
},
FusionAlgorithm: vector.FusionAlgorithmRRF,
})
}
```
----------------------------------------
TITLE: Querying Sparse Index in PHP using Upstash Vector SDK
DESCRIPTION: This code snippet shows how to query a sparse vector index using the Upstash Vector PHP SDK. It uses a SparseVector object to represent the query vector.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/php/commands/query.mdx#2025-04-11_snippet_1
LANGUAGE: php
CODE:
```
use Upstash\Vector\Index;
use Upstash\Vector\VectorQuery;
use Upstash\Vector\SparseVector;
$index = new Index(
url: "",
token: "",
);
$results = $index->query(new VectorQuery(
sparseVector: new SparseVector(
indices: [1, 2, 3],
values: [5.0, 6.0, 7.0],
),
topK: 15,
));
```
----------------------------------------
TITLE: Upserting Vectors with Metadata in Python
DESCRIPTION: Example showing how to insert or update a vector with metadata in Python. The metadata includes a URL that can be retrieved later with queries.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/metadata.mdx#2025-04-11_snippet_0
LANGUAGE: python
CODE:
```
from upstash_vector import Index
index = Index(
url="UPSTASH_VECTOR_REST_URL",
token="UPSTASH_VECTOR_REST_TOKEN",
)
index.upsert(
[("id-0", [0.9215, 0.3897]), {"url": "https://imgur.com/z9AVZLb"}],
)
```
----------------------------------------
TITLE: Sparse Vector Index Operations in PHP
DESCRIPTION: Demonstrates how to work with sparse indexes by upserting vectors with specific indices and their corresponding values using the SparseVector class.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/php/commands/upsert-vectors.mdx#2025-04-11_snippet_4
LANGUAGE: php
CODE:
```
use Upstash\Vector\Index;
use Upstash\Vector\VectorUpsert;
use Upstash\Vector\SparseVector;
$index = new Index(
url: "",
token: "",
);
$index->upsert(new VectorUpsert(
id: '1',
sparseVector: new SparseVector(
indices: [0, 1],
values: [1.0, 2.0],
),
));
```
----------------------------------------
TITLE: Using Namespaces with Upstash Vector in Python
DESCRIPTION: This code demonstrates how to upsert and query vectors within a specified namespace in Python. It creates a namespace called 'ns' if it doesn't exist, inserts a vector with ID 'id-0', and then queries that namespace for similar vectors.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/namespaces.mdx#2025-04-11_snippet_0
LANGUAGE: python
CODE:
```
from upstash_vector import Index
index = Index(
url="UPSTASH_VECTOR_REST_URL",
token="UPSTASH_VECTOR_REST_TOKEN",
)
index.upsert(
[("id-0", [0.9215, 0.3897])],
namespace="ns",
)
index.query(
[0.9215, 0.3897],
top_k=5,
namespace="ns",
)
```
----------------------------------------
TITLE: Upserting Vectors Using Vector Object in Python
DESCRIPTION: Demonstrates how to upsert vectors using the Vector class object. Creates 100 vectors with random values, each containing an ID, vector data, metadata, and unstructured data.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/py/example_calls/upsert.mdx#2025-04-11_snippet_0
LANGUAGE: python
CODE:
```
import random
from upstash_vector import Index, Vector
index = Index.from_env()
dimension = 128 # Adjust based on your index's dimension
upsert_amount = 100
vectors = [
Vector(
id=f"generated-id-{i}",
vector=[random.random() for _ in range(dimension)],
metadata={"some_field": f"some_value-{i}"},
data=f"some-unstructured-data-{i}",
)
for i in range(upsert_amount)
]
index.upsert(vectors=vectors)
```
----------------------------------------
TITLE: Querying Text Data with Embedding Models in JavaScript
DESCRIPTION: Shows how to query Upstash Vector with raw text in JavaScript. The query text will be automatically converted to a vector embedding by the selected model for similarity search.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/embeddingmodels.mdx#2025-04-11_snippet_6
LANGUAGE: javascript
CODE:
```
import { Index } from "@upstash/vector"
const index = new Index({
url: "UPSTASH_VECTOR_REST_URL",
token: "UPSTASH_VECTOR_REST_TOKEN",
})
await index.query({
data: "What is Upstash?",
topK: 1,
includeMetadata: true,
})
```
----------------------------------------
TITLE: Querying Sparse Vectors with Upstash Vector in Go
DESCRIPTION: This snippet shows how to query sparse vectors in an Upstash Vector index using Go. It creates an Index object and uses the Query method with a SparseVector to search for similar vectors.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/sparseindexes.mdx#2025-04-11_snippet_13
LANGUAGE: go
CODE:
```
package main
import (
"github.com/upstash/vector-go"
)
func main() {
index := vector.NewIndex(
"UPSTASH_VECTOR_REST_URL",
"UPSTASH_VECTOR_REST_TOKEN",
)
scores, err := index.Query(vector.Query{
SparseVector: &vector.SparseVector{
Indices: []int32{3, 5},
Values: []float32{0.3, 05},
},
TopK: 5,
IncludeMetadata: true,
})
}
```
----------------------------------------
TITLE: Query Response with Metadata
DESCRIPTION: Example JSON response from a vector query that includes metadata. The response contains vector IDs, similarity scores, and the metadata associated with each vector.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/metadata.mdx#2025-04-11_snippet_10
LANGUAGE: json
CODE:
```
{
"result": [
{
"id": "id-0",
"score": 1,
"metadata": {
"url": "https://imgur.com/z9AVZLb"
}
},
{
"id": "id-3",
"score": 0.99961007,
"metadata": {
"url": "https://imgur.com/zfOPmnI"
}
}
]
}
```
----------------------------------------
TITLE: Fetching Data from Upstash Vector Index
DESCRIPTION: TypeScript code demonstrating how to fetch data from an Upstash Vector index with options for including metadata and vectors.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/ts/overview-backup.mdx#2025-04-11_snippet_4
LANGUAGE: typescript
CODE:
```
await index.fetch([....], { includeMetadata: true, includeVectors: true });
```
----------------------------------------
TITLE: Querying Text Data with Upstash Vector in JavaScript
DESCRIPTION: This snippet shows how to query text data in an Upstash Vector index using JavaScript. It creates an Index object and uses the query method with text data to search for similar vectors.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/sparseindexes.mdx#2025-04-11_snippet_17
LANGUAGE: javascript
CODE:
```
import { Index } from "@upstash/vector"
const index = new Index({
url: "UPSTASH_VECTOR_REST_URL",
token: "UPSTASH_VECTOR_REST_TOKEN",
})
await index.query(
{
data: "Upstash Vector",
topK: 1,
},
)
```
----------------------------------------
TITLE: Retrieving Vector Range with Metadata using curl
DESCRIPTION: Example showing how to retrieve a range of vectors with their metadata using curl. The request specifies a starting cursor, a limit of 3 records, and includes metadata in the response.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/metadata.mdx#2025-04-11_snippet_20
LANGUAGE: shell
CODE:
```
curl $UPSTASH_VECTOR_REST_URL/range \
-H "Authorization: Bearer $UPSTASH_VECTOR_REST_TOKEN" \
-d '{ "cursor" : "0", "limit" : 3, "includeMetadata": true}'
```
----------------------------------------
TITLE: Querying with Metadata Filter in Go
DESCRIPTION: Example of how to perform a vector similarity search with metadata filtering using the Upstash Vector Go client. The query includes a vector, filter condition, top-k limit, and metadata inclusion.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/filtering.mdx#2025-04-11_snippet_3
LANGUAGE: go
CODE:
```
package main
import (
"github.com/upstash/vector-go"
)
func main() {
index := vector.NewIndex("UPSTASH_VECTOR_REST_URL", "UPSTASH_VECTOR_REST_TOKEN")
index.Query(vector.Query{
Vector: []float32{0.9215, 0.3897},
Filter: `population >= 1000000 AND geography.continent = 'Asia'`,
TopK: 5,
IncludeMetadata: true,
})
}
```
----------------------------------------
TITLE: Upserting Vectors Using Dictionaries in Python
DESCRIPTION: Illustrates vector upsert using dictionary format. Each dictionary contains named fields for ID, vector data, metadata, and unstructured data.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/py/example_calls/upsert.mdx#2025-04-11_snippet_2
LANGUAGE: python
CODE:
```
import random
from upstash_vector import Index
index = Index.from_env()
dimension = 128 # Adjust based on your index's dimension
upsert_amount = 100
vectors = [
{
"id": f"generated-id-{i}",
"vector": [random.random() for _ in range(dimension)],
"metadata": {"some_field": f"some_value-{i}"},
"data": f"some-unstructured-data-{i}",
}
for i in range(upsert_amount)
]
index.upsert(vectors=vectors)
```
----------------------------------------
TITLE: Querying Sparse Vectors with Upstash Vector in Python
DESCRIPTION: This snippet shows how to query sparse vectors in an Upstash Vector index using Python. It creates an Index object and uses the query method with a SparseVector to search for similar vectors.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/sparseindexes.mdx#2025-04-11_snippet_11
LANGUAGE: python
CODE:
```
from upstash_vector import Index
from upstash_vector.types import SparseVector
index = Index(
url="UPSTASH_VECTOR_REST_URL",
token="UPSTASH_VECTOR_REST_TOKEN",
)
index.query(
sparse_vector=SparseVector([3, 5], [0.3, 0.5]),
top_k=5,
include_metadata=True,
)
```
----------------------------------------
TITLE: Hybrid Vector Index Operations in PHP
DESCRIPTION: Shows how to work with hybrid indexes that require both sparse and dense vectors. Combines regular vector data with sparse vector data in a single upsert operation.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/php/commands/upsert-vectors.mdx#2025-04-11_snippet_5
LANGUAGE: php
CODE:
```
use Upstash\Vector\Index;
use Upstash\Vector\VectorUpsert;
use Upstash\Vector\SparseVector;
use function Upstash\Vector\createRandomVector;
$index = new Index(
url: "",
token: "",
);
$index->upsert(new VectorUpsert(
id: '1',
vector: createRandomVector(dimensions: 1536),
sparseVector: new SparseVector(
indices: [0, 1],
values: [1.0, 2.0],
),
));
```
----------------------------------------
TITLE: Querying Upstash Vector Index with Options
DESCRIPTION: TypeScript code demonstrating how to query an Upstash Vector index with various options such as topK and vector values.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/ts/overview-backup.mdx#2025-04-11_snippet_6
LANGUAGE: typescript
CODE:
```
> await index.query({ topK: 3, vector: [ ... ]})
{
matches: [
{
id: '6345',
score: 1.00000012,
vector: [],
metadata: undefined
},
{
id: '1233',
score: 1.00000012,
vector: [],
metadata: undefined
},
{
id: '4142',
score: 1.00000012,
vector: [],
metadata: undefined
}
],
namespace: ''
}
```
----------------------------------------
TITLE: Upserting Vectors with Data and Metadata
DESCRIPTION: Shows how to upsert vectors with both data and metadata fields. The example demonstrates creating vectors with numerical values, associated metadata like URLs, and arbitrary data strings.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/metadata.mdx#2025-04-11_snippet_22
LANGUAGE: python
CODE:
```
from upstash_vector import Index
index = Index(
url="UPSTASH_VECTOR_REST_URL",
token="UPSTASH_VECTOR_REST_TOKEN",
)
index.upsert(
[
{
"id": "id-0",
"vector": [0.9215, 0.3897],
"metadata": {"url": "https://imgur.com/z9AVZLb"},
"data": "data-0",
},
{
"id": "id-1",
"vector": [0.3897, 0.9215],
"data": "data-1",
},
],
)
```
LANGUAGE: javascript
CODE:
```
import { Index } from "@upstash/vector"
const index = new Index({
url: "UPSTASH_VECTOR_REST_URL",
token: "UPSTASH_VECTOR_REST_TOKEN",
})
await index.upsert([
{
id: "id-0",
vector: [0.9215, 0.3897],
metadata: {"url": "https://imgur.com/z9AVZLb"},
data: "data-0",
},
{
id: "id-1",
vector: [0.3897, 0.9215],
data: "data-1",
},
])
```
LANGUAGE: php
CODE:
```
use Upstash\Vector\Index;
use Upstash\Vector\VectorUpsert;
$index = new Index(
url: 'UPSTASH_VECTOR_REST_URL',
token: 'UPSTASH_VECTOR_REST_TOKEN',
);
$index->upsertMany([
new VectorUpsert(
id: 'id-0',
vector: [0.9215, 0.3897],
data: 'data-0',
),
new VectorUpsert(
id: 'id-1',
vector: [0.3897, 0.9215],
data: 'data-1',
),
]);
```
LANGUAGE: shell
CODE:
```
curl $UPSTASH_VECTOR_REST_URL/upsert \
-X POST \
-H "Authorization: Bearer $UPSTASH_VECTOR_REST_TOKEN" \
-d '[
{
"id": "id-0",
"vector": [0.9215, 0.3897],
"metadata": {"url": "https://imgur.com/z9AVZLb"},
"data": "data-0"
},
{
"id": "id-1",
"vector": [0.3897, 0.9215],
"data": "data-1"
}
]'
```
----------------------------------------
TITLE: Updating Vector Data and Metadata in Upstash Vector Using Python
DESCRIPTION: This example demonstrates how to update both the metadata and data of a vector in Upstash Vector database. The update method allows you to replace existing values with new ones, returning the updated vector information.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/py/example_calls/update.mdx#2025-04-11_snippet_0
LANGUAGE: python
CODE:
```
from upstash_vector import Index
index = Index.from_env()
updated = index.update(
id="id1",
metadata={"new": "metadata"},
data="new-data",
)
print(updated)
```
----------------------------------------
TITLE: Creating an Upstash Vector Store with Custom Namespace
DESCRIPTION: Example showing how to initialize an Upstash Vector Store with a custom namespace, which allows for organizing and separating different collections of vectors within the same index.
SOURCE: https://github.com/upstash/docs/blob/main/vector/integrations/llamaindex.mdx#2025-04-11_snippet_4
LANGUAGE: python
CODE:
```
vector_store = UpstashVectorStore(
url="your_upstash_url",
token="your_upstash_token",
namespace="your_namespace"
)
```
----------------------------------------
TITLE: Demonstrating Dense vs Sparse Vector Representation in Python
DESCRIPTION: Shows the difference between dense and sparse vector representations, where sparse vectors use two arrays - one for indices and one for corresponding values.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/sparseindexes.mdx#2025-04-11_snippet_0
LANGUAGE: python
CODE:
```
dense = [0.1, 0.3, , ...thousands of non-zero values..., 0.5, 0.2]
sparse = (
[23, 42, 5523, 123987, 240001], # some low number of dimension indices
[0.1, 0.3, 0.1, 0.2, 0.5], # non-zero values corresponding to dimensions
)
```
----------------------------------------
TITLE: Using command-level type definitions for metadata
DESCRIPTION: Applying type safety to specific commands when you don't want to define metadata types at the index level.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/ts/getting-started.mdx#2025-04-11_snippet_6
LANGUAGE: typescript
CODE:
```
import { Index } from "@upstash/vector";
type Metadata = { genre: string, year: number };
const index = new Index();
index.upsert({ id: 1, vector: [...], metadata: {
genre: "comedy",
year: 1990
}});
```
----------------------------------------
TITLE: Upserting a Single Vector in Upstash Vector Database
DESCRIPTION: This example demonstrates how to upsert a single vector with an ID, vector data, and metadata. The metadata includes properties like title, genre, and category that can be used for filtering or providing additional context for the vector.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/ts/commands/upsert.mdx#2025-04-11_snippet_0
LANGUAGE: typescript
CODE:
```
await index.upsert({
id: "1234",
vector: [0.1, 0.2, 0.3, 0.4, 0.5],
metadata: {
title: "Lord of The Rings",
genre: "drama",
category: "classic",
},
});
```
----------------------------------------
TITLE: Querying Text Data with Upstash Vector in Go
DESCRIPTION: This snippet demonstrates how to query text data in an Upstash Vector index using Go. It creates an Index object and uses the QueryData method with text data to search for similar vectors.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/sparseindexes.mdx#2025-04-11_snippet_18
LANGUAGE: go
CODE:
```
package main
import (
"github.com/upstash/vector-go"
)
func main() {
index := vector.NewIndex(
"UPSTASH_VECTOR_REST_URL",
"UPSTASH_VECTOR_REST_TOKEN",
)
scores, err := index.QueryData(vector.QueryData{
Data: "Upstash Vector",
TopK: 5,
})
}
```
----------------------------------------
TITLE: Upserting Text Data with Embedding Models using cURL
DESCRIPTION: Shows how to upsert raw text data into Upstash Vector using cURL requests. The text will be automatically converted to vector embeddings by the selected model.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/embeddingmodels.mdx#2025-04-11_snippet_4
LANGUAGE: shell
CODE:
```
curl $UPSTASH_VECTOR_REST_URL/upsert-data \
-X POST \
-H "Authorization: Bearer $UPSTASH_VECTOR_REST_TOKEN" \
-d '{"id": "1", "data": "Upstash is a serverless data platform.", "metadata": {"field": "value"}}'
```
----------------------------------------
TITLE: Querying Range Vectors using cURL
DESCRIPTION: Makes a GET request to retrieve vector data from the default namespace with pagination and metadata inclusion. This example uses a cursor of "0" to start from the beginning and limits the results to 2 items per page.
SOURCE: https://github.com/upstash/docs/blob/main/vector/api/endpoints/range.mdx#2025-04-11_snippet_0
LANGUAGE: sh
CODE:
```
curl $UPSTASH_VECTOR_REST_URL/range \
-H "Authorization: Bearer $UPSTASH_VECTOR_REST_TOKEN" \
-d '{ "cursor": "0", "limit": 2, "includeMetadata": true }'
```
----------------------------------------
TITLE: Upserting Text Data with Embedding Models in PHP
DESCRIPTION: Shows how to upsert raw text data into Upstash Vector using PHP. The text will be automatically converted to vector embeddings by the selected model.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/embeddingmodels.mdx#2025-04-11_snippet_3
LANGUAGE: php
CODE:
```
use Upstash\Vector\Index;
use Upstash\Vector\DataUpsert;
$index = new Index(
url: 'UPSTASH_VECTOR_REST_URL',
token: 'UPSTASH_VECTOR_REST_TOKEN',
);
$index->upsertData(new DataUpsert(
id: 'id-0',
data: 'Upstash is a serverless data platform.',
metadata: [
'field' => 'value',
],
));
```
----------------------------------------
TITLE: Upserting Vectors with Metadata in PHP
DESCRIPTION: Example showing how to insert or update a vector with metadata in PHP. This creates a random vector with associated metadata containing a URL.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/metadata.mdx#2025-04-11_snippet_3
LANGUAGE: php
CODE:
```
use Upstash\Vector\Index;
use Upstash\Vector\VectorUpsert;
use function Upstash\Vector\createRandomVector;
$index = new Index(
url: 'UPSTASH_VECTOR_REST_URL',
token: 'UPSTASH_VECTOR_REST_TOKEN',
);
$index->upsert(new VectorUpsert(
id: 'id-0',
vector: createRandomVector(384),
metadata: [
'url' => "https://imgur.com/z9AVZLb",
],
));
```
----------------------------------------
TITLE: Upserting Single Data Item with Embedding Model in PHP
DESCRIPTION: This snippet demonstrates how to upsert a single data item using the Upstash Vector SDK in PHP. It initializes an Index object and uses the upsertData() method to insert or update data with automatic vector generation.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/php/commands/upsert-data.mdx#2025-04-11_snippet_0
LANGUAGE: php
CODE:
```
use Upstash\Vector\Index;
use Upstash\Vector\DataUpsert;
$index = new Index(
url: "",
token: "",
);
$index->upsertData(new DataUpsert(
id: '1',
data: 'The capital of Japan is Tokyo',
));
```
----------------------------------------
TITLE: Upserting Text Data with Upstash Vector in JavaScript
DESCRIPTION: This snippet shows how to upsert text data into an Upstash Vector index using JavaScript. It creates an Index object and uses the upsert method to add a vector with text data.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/sparseindexes.mdx#2025-04-11_snippet_7
LANGUAGE: javascript
CODE:
```
import { Index } from "@upstash/vector"
const index = new Index({
url: "UPSTASH_VECTOR_REST_URL",
token: "UPSTASH_VECTOR_REST_TOKEN",
})
await index.upsert([
{
id: 'id-0',
data: "Upstash Vector provides dense and sparse embedding models.",
}
])
```
----------------------------------------
TITLE: Querying Upstash Vector Index with Type-Safe Metadata in TypeScript
DESCRIPTION: This example demonstrates how to use TypeScript generics to provide type safety for metadata in query results. It defines a custom Metadata type with specific field types, then passes it as a type parameter to the query method for improved type checking.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/ts/commands/query.mdx#2025-04-11_snippet_2
LANGUAGE: typescript
CODE:
```
type Metadata = {
title: string,
genre: 'sci-fi' | 'fantasy' | 'horror' | 'action'
}
const results = await index.query({
vector: [
... // query embedding
],
includeVectors: true,
topK: 1,
filter: "genre = 'fantasy' and title = 'Lord of the Rings'"
})
if (results[0].metadata) {
// Since we passed the Metadata type parameter above,
// we can interact with metadata fields without having to
// do any typecasting.
const { title, genre } = results[0].metadata;
console.log(`The best match in fantasy was ${title}`)
}
```
----------------------------------------
TITLE: Upserting Text Data with Upstash Vector in Go
DESCRIPTION: This snippet demonstrates how to upsert text data into an Upstash Vector index using Go. It creates an Index object and uses the UpsertDataMany method to add multiple vectors with text data.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/sparseindexes.mdx#2025-04-11_snippet_8
LANGUAGE: go
CODE:
```
package main
import (
"github.com/upstash/vector-go"
)
func main() {
index := vector.NewIndex(
"UPSTASH_VECTOR_REST_URL",
"UPSTASH_VECTOR_REST_TOKEN",
)
err := index.UpsertDataMany([]vector.UpsertData{
{
Id: "id-0",
Data: "Upstash Vector provides sparse embedding models.",
},
{
Id: "id-1",
Data: "You can upsert text data with these embedding models.",
},
})
}
```
----------------------------------------
TITLE: Retrieving Vector Index Statistics with Python
DESCRIPTION: Example showing how to use the info() method to get statistical information about an Upstash vector index. The code demonstrates connecting to the index and retrieving details like vector count, size, dimensions, similarity function, and namespace statistics.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/py/example_calls/info.mdx#2025-04-11_snippet_0
LANGUAGE: python
CODE:
```
from upstash_vector import Index
index = Index.from_env()
from upstash_vector import Index
index = Index.from_env()
# Get statistical information about the index
info_result = index.info()
# Display the info result
print("Vector Count:", info_result.vector_count)
print("Pending Vector Count:", info_result.pending_vector_count)
print("Index Size:", info_result.index_size)
print("Dimension:", info_result.dimension)
print("Similarity Function:", info_result.similarity_function)
for ns, ns_info in info_result.namespaces.items():
print("Namespace:", ns, "Vector Count:", ns_info.vector_count)
print("Namespace:", ns, "Pending Vector Count:", ns_info.pending_vector_count)
```
----------------------------------------
TITLE: Upserting Multiple Data Items for Automatic Embedding in Upstash Vector Database
DESCRIPTION: This example shows how to upsert multiple data items using text data instead of vector embeddings. Upstash will generate embeddings for both text entries, demonstrating batch processing of text-to-vector conversion.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/ts/commands/upsert.mdx#2025-04-11_snippet_5
LANGUAGE: typescript
CODE:
```
await index.upsert([
{
id: "6789",
data: "'Harry Potter' follows the journey of a young wizard, Harry Potter, as he attends Hogwarts School of Witchcraft and Wizardry, forms deep friendships, and confronts the dark wizard Voldemort, who seeks immortality and domination over the magical world.",
},
{
id: "1234",
data: "'The Lord of the Rings' follows Frodo Baggins and his allies on a quest to destroy a powerful ring and save Middle-earth from the dark lord Sauron.",
metadata: {
title: "Lord of The Rings",
genre: "drama",
category: "classic",
},
},
]);
```
----------------------------------------
TITLE: Setting Up Environment Variables for Upstash Vector and OpenAI
DESCRIPTION: Example of environment variables that need to be set in a .env file, including Upstash Vector REST credentials and OpenAI API key for embedding generation.
SOURCE: https://github.com/upstash/docs/blob/main/vector/integrations/llamaindex.mdx#2025-04-11_snippet_1
LANGUAGE: plaintext
CODE:
```
UPSTASH_VECTOR_REST_URL=your_upstash_url
UPSTASH_VECTOR_REST_TOKEN=your_upstash_token
OPENAI_API_KEY=your_openai_api_key
```
----------------------------------------
TITLE: Querying Upstash Vector Index using curl
DESCRIPTION: Code for performing a similarity search in an Upstash Vector Index using HTTP API with curl. It demonstrates how to make a direct REST API call to query the index with a vector, limit results, and include metadata.
SOURCE: https://github.com/upstash/docs/blob/main/vector/overall/getstarted.mdx#2025-04-11_snippet_9
LANGUAGE: shell
CODE:
```
curl $UPSTASH_VECTOR_REST_URL/query \
-H "Authorization: Bearer $UPSTASH_VECTOR_REST_TOKEN" \
-d '{"vector": [0.6, 0.8], "topK": 3, "includeMetadata": "true"}'
```
----------------------------------------
TITLE: Upserting Multiple Vectors using cURL
DESCRIPTION: Example of upserting multiple dense vectors with metadata using cURL to the default namespace.
SOURCE: https://github.com/upstash/docs/blob/main/vector/api/endpoints/upsert.mdx#2025-04-11_snippet_0
LANGUAGE: sh
CODE:
```
curl $UPSTASH_VECTOR_REST_URL/upsert \
-X POST \
-H "Authorization: Bearer $UPSTASH_VECTOR_REST_TOKEN" \
-d '[
{ "id": "id-0", "vector": [0.1, 0.2], "metadata": { "link": "upstash.com" } },
{ "id": "id-1", "vector": [0.2, 0.3] }
]'
```
----------------------------------------
TITLE: Upserting a Single Data Item for Automatic Embedding in Upstash Vector Database
DESCRIPTION: This example demonstrates how to upsert a single data item using the text data directly instead of providing vector embeddings. Upstash will automatically generate the embeddings from the text data using its embedding service.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/ts/commands/upsert.mdx#2025-04-11_snippet_4
LANGUAGE: typescript
CODE:
```
await index.upsert({
id: "1234",
data: "'The Lord of the Rings' follows Frodo Baggins and his allies on a quest to destroy a powerful ring and save Middle-earth from the dark lord Sauron.",
metadata: {
title: "Lord of The Rings",
genre: "drama",
category: "classic",
},
});
```
----------------------------------------
TITLE: Upserting Text Data with Upstash Vector in PHP
DESCRIPTION: This snippet shows how to upsert text data into an Upstash Vector index using PHP. It creates an Index object and uses the upsertDataMany method to add multiple vectors with text data.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/sparseindexes.mdx#2025-04-11_snippet_9
LANGUAGE: php
CODE:
```
use Upstash\Vector\Index;
use Upstash\Vector\DataUpsert;
$index = new Index(
url: 'UPSTASH_VECTOR_REST_URL',
token: 'UPSTASH_VECTOR_REST_TOKEN',
);
$index->upsertDataMany([
new DataUpsert(
id: 'id-0',
data: 'Upstash Vector provides sparse embedding models.',
),
new DataUpsert(
id: 'id-1',
data: 'You can upsert text data with these embedding models.',
),
]);
```
----------------------------------------
TITLE: Specifying a Namespace for Vector Updates in Upstash Vector
DESCRIPTION: This example demonstrates how to specify a namespace when updating vectors in Upstash Vector. When no namespace is provided, the operation will use the default namespace.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/py/example_calls/update.mdx#2025-04-11_snippet_2
LANGUAGE: python
CODE:
```
index.update(..., namespace="ns")
```
----------------------------------------
TITLE: Upserting Vectors with Metadata in JavaScript
DESCRIPTION: Example showing how to insert or update a vector with metadata in JavaScript. The metadata contains a URL attribute that can be used for identification or filtering.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/metadata.mdx#2025-04-11_snippet_1
LANGUAGE: javascript
CODE:
```
import { Index } from "@upstash/vector"
const index = new Index({
url: "UPSTASH_VECTOR_REST_URL",
token: "UPSTASH_VECTOR_REST_TOKEN",
})
await index.upsert({
"id": "id-0",
vector: [0.9215, 0.3897],
metadata: {
url: "https://imgur.com/z9AVZLb",
},
})
```
----------------------------------------
TITLE: Retrieving Vector Index Information with Upstash in TypeScript
DESCRIPTION: This code snippet demonstrates how to retrieve information about a vector index including total vector count, pending vectors, index size, dimension, similarity function, and namespace details. The example shows the structure of the returned data object.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/ts/commands/info.mdx#2025-04-11_snippet_0
LANGUAGE: typescript
CODE:
```
const infoResponse = await index.info();
/*
{
vectorCount: 17,
pendingVectorCount: 0,
indexSize: 551158,
dimension: 1536,
similarityFunction: "COSINE",
namespaces: {
"": { // default namespace
vectorCount: 10,
pendingVectorCount: 0,
},
"my-namespace": {
vectorCount: 7,
pendingVectorCount: 0,
}
}
}
*/
```
----------------------------------------
TITLE: Inserting Data into Upstash Vector Index using curl
DESCRIPTION: Code for upserting vector data into an Upstash Vector Index using HTTP API with curl. It demonstrates how to make a direct REST API call to insert a vector with ID, embedding values, and metadata.
SOURCE: https://github.com/upstash/docs/blob/main/vector/overall/getstarted.mdx#2025-04-11_snippet_4
LANGUAGE: shell
CODE:
```
curl $UPSTASH_VECTOR_REST_URL/upsert \
-X POST \
-H "Authorization: Bearer $UPSTASH_VECTOR_REST_TOKEN" \
-d '{"id": "1", "vector": [0.6, 0.8], "metadata": {"field": "value"}}'
```
----------------------------------------
TITLE: Upserting Vectors to a Specific Namespace in Upstash Vector Database
DESCRIPTION: This example demonstrates how to upsert vectors to a specific namespace. Namespaces allow for logical separation of data within the same index, which can be useful for multi-tenancy or organizing vectors.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/ts/commands/upsert.mdx#2025-04-11_snippet_2
LANGUAGE: typescript
CODE:
```
await index.upsert([
{
id: "6789",
vector: [0.6, 0.7, 0.8, 0.9, 0.9],
},
], { namespace: "my-namespace" });
```
----------------------------------------
TITLE: Configuring Multiple Vector Connections in Laravel
DESCRIPTION: Example of configuring multiple Upstash Vector connections in a Laravel application, allowing for interaction with different vector databases.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/php/laravel.mdx#2025-04-11_snippet_6
LANGUAGE: php
CODE:
```
return [
'default' => env('UPSTASH_VECTOR_CONNECTION', 'default'),
'connections' => [
'default' => [
'url' => env('UPSTASH_VECTOR_REST_URL'),
'token' => env('UPSTASH_VECTOR_REST_TOKEN'),
],
'another' => [
'url' => env('SECOND_UPSTASH_VECTOR_REST_URL'),
'token' => env('SECOND_UPSTASH_VECTOR_REST_TOKEN'),
],
],
];
```
----------------------------------------
TITLE: Upserting Vectors with Metadata in Go
DESCRIPTION: Example showing how to insert or update a vector with metadata in Go. The upsert operation includes a vector ID, the vector itself, and metadata with a URL.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/metadata.mdx#2025-04-11_snippet_2
LANGUAGE: go
CODE:
```
package main
import (
"github.com/upstash/vector-go"
)
func main() {
index := vector.NewIndex("UPSTASH_VECTOR_REST_URL", "UPSTASH_VECTOR_REST_TOKEN")
index.Upsert(vector.Upsert{
Id: "id-0",
Vector: []float32{0.9215, 0.3897},
Metadata: map[string]any{"url": "https://imgur.com/z9AVZLb"},
})
}
```
----------------------------------------
TITLE: Upserting Text Data with Upstash Vector using cURL
DESCRIPTION: This snippet demonstrates how to upsert text data into an Upstash Vector index using cURL. It sends a POST request to the upsert-data endpoint with multiple vectors containing text data.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/sparseindexes.mdx#2025-04-11_snippet_10
LANGUAGE: shell
CODE:
```
curl $UPSTASH_VECTOR_REST_URL/upsert-data \
-H "Authorization: Bearer $UPSTASH_VECTOR_REST_TOKEN" \
-d '[
{"id": "id-0", "data": "Upstash Vector provides sparse embedding models."},
{"id": "id-1", "data": "You can upsert text data with these embedding models."}
]'
```
----------------------------------------
TITLE: Fetching Vectors by ID Prefix with Namespace in PHP using Upstash Vector
DESCRIPTION: This code demonstrates fetching vectors by ID prefix within a specific namespace in an Upstash Vector database. It combines the namespace() method with VectorFetchByPrefix to retrieve vectors with matching ID prefixes from a designated namespace.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/php/commands/fetch.mdx#2025-04-11_snippet_3
LANGUAGE: php
CODE:
```
use Upstash\Vector\Index;
use Upstash\Vector\VectorFetchByPrefix;
$index = new Index(
url: "",
token: "",
);
$results = $index->namespace('my-namespace')->fetch(new VectorFetchByPrefix(
prefix: 'users:',
includeMetadata: true, // (optional) if true the fetch results will contain metadata.
includeVectors: true, // (optional) if true the fetch results will contain the indexed vectors.
includeData: true, // (optional) if true the fetch results will contain the string data.
));
```
----------------------------------------
TITLE: Retrieving Vector Range with Metadata in Python
DESCRIPTION: Example showing how to retrieve a range of vectors with their metadata in Python. The range operation retrieves a specified number of vectors starting from a cursor position.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/metadata.mdx#2025-04-11_snippet_16
LANGUAGE: python
CODE:
```
from upstash_vector import Index
index = Index(
url="UPSTASH_VECTOR_REST_URL",
token="UPSTASH_VECTOR_REST_TOKEN",
)
index.range(
cursor="0",
limit=3,
include_metadata=True,
)
```
----------------------------------------
TITLE: Querying Range Vectors with Namespace using cURL
DESCRIPTION: Makes a GET request to retrieve vector data from a specific namespace called "ns" with pagination and metadata inclusion. This example specifies the namespace in the URL path while maintaining the same query parameters.
SOURCE: https://github.com/upstash/docs/blob/main/vector/api/endpoints/range.mdx#2025-04-11_snippet_1
LANGUAGE: sh
CODE:
```
curl $UPSTASH_VECTOR_REST_URL/range/ns \
-H "Authorization: Bearer $UPSTASH_VECTOR_REST_TOKEN" \
-d '{ "cursor": "0", "limit": 2, "includeMetadata": true }'
```
----------------------------------------
TITLE: Querying Text Data with Embedding Models in Go
DESCRIPTION: Shows how to query Upstash Vector with raw text in Go. The query text will be automatically converted to a vector embedding by the selected model for similarity search.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/embeddingmodels.mdx#2025-04-11_snippet_7
LANGUAGE: go
CODE:
```
package main
import (
"github.com/upstash/vector-go"
)
func main() {
index := vector.NewIndex("UPSTASH_VECTOR_REST_URL", "UPSTASH_VECTOR_REST_TOKEN")
index.QueryData(vector.QueryData{
Data: "What is Upstash?",
TopK: 1,
IncludeMetadata: true,
})
}
```
----------------------------------------
TITLE: Using Namespaces with Upstash Vector in curl
DESCRIPTION: This curl example demonstrates how to perform vector operations within a specific namespace. It shows how to upsert a vector with ID 'id-0' and query for similar vectors within the 'ns' namespace.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/namespaces.mdx#2025-04-11_snippet_4
LANGUAGE: shell
CODE:
```
curl $UPSTASH_VECTOR_REST_URL/upsert/ns \
-X POST \
-H "Authorization: Bearer $UPSTASH_VECTOR_REST_TOKEN" \
-d '{"id":"id-0", "vector":[0.9215,0.3897]}'
curl $UPSTASH_VECTOR_REST_URL/query/ns \
-H "Authorization: Bearer $UPSTASH_VECTOR_REST_TOKEN" \
-d '{"vector":[0.9215,0.3897], "topK" : 5}'
```
----------------------------------------
TITLE: Using Namespaces with Upstash Vector in JavaScript
DESCRIPTION: This code shows how to use namespaces in JavaScript. It creates an index instance, defines a namespace called 'ns', and performs upsert and query operations specifically within that namespace.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/namespaces.mdx#2025-04-11_snippet_1
LANGUAGE: javascript
CODE:
```
import { Index } from "@upstash/vector"
const index = new Index({
url: "UPSTASH_VECTOR_REST_URL",
token: "UPSTASH_VECTOR_REST_TOKEN",
})
const namespace = index.namespace("ns")
await namespace.upsert({
id: "id-0",
vector: [0.9215, 0.3897],
})
await namespace.query({
vector: [0.9215, 0.3897],
topK: 5,
})
```
----------------------------------------
TITLE: Querying Vector Data in Specific Namespace with curl in Upstash
DESCRIPTION: curl command to query vector data in a specific namespace 'ns', with the same query parameters as the basic example.
SOURCE: https://github.com/upstash/docs/blob/main/vector/api/endpoints/query-data.mdx#2025-04-11_snippet_1
LANGUAGE: sh
CODE:
```
curl $UPSTASH_VECTOR_REST_URL/query-data/ns \
-X POST \
-H "Authorization: Bearer $UPSTASH_VECTOR_REST_TOKEN" \
-d '{ "data": "What is Upstash?", "topK": 2, "includeMetadata": true }'
```
----------------------------------------
TITLE: Initializing Upstash Vector Index from Environment Variables
DESCRIPTION: Alternative initialization method that automatically loads the Upstash Vector credentials from environment variables. This is useful for maintaining security by not hardcoding credentials in your code.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/py/gettingstarted.mdx#2025-04-11_snippet_2
LANGUAGE: python
CODE:
```
from upstash_vector import Index
index = Index.from_env()
```
----------------------------------------
TITLE: Upserting Single Data Item with Namespace in PHP
DESCRIPTION: This snippet shows how to upsert a single data item using a namespace in Upstash Vector. It creates an Index object and uses the namespace() method before calling upsertData() to insert or update data within a specific namespace.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/php/commands/upsert-data.mdx#2025-04-11_snippet_1
LANGUAGE: php
CODE:
```
use Upstash\Vector\Index;
use Upstash\Vector\DataUpsert;
$index = new Index(
url: "",
token: "",
);
$index->namespace('my-namespace')->upsertData(new DataUpsert(
id: '1',
data: 'The capital of Japan is Tokyo',
));
```
----------------------------------------
TITLE: Fetching Namespace Information with Upstash Vector PHP SDK
DESCRIPTION: This snippet demonstrates how to use the getNamespaceInfo() method to retrieve information about specific namespaces or the default namespace. It requires an initialized Index instance.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/php/commands/info.mdx#2025-04-11_snippet_2
LANGUAGE: php
CODE:
```
use Upstash\Vector\Index;
$index = new Index(
url: "",
token: "",
);
// Fetch the information of the default namespace.
$defaultNamespaceInfo = $index->getNamespaceInfo();
// Fetch the information on a specific namespace.
$myNamespaceInfo = $index->namespace('my-namespace')->getNamespaceInfo();
```
----------------------------------------
TITLE: Retrieving Vector Range with Metadata in Go
DESCRIPTION: Example showing how to retrieve a range of vectors with their metadata in Go. The range operation fetches up to 3 vectors starting from cursor position '0'.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/metadata.mdx#2025-04-11_snippet_18
LANGUAGE: go
CODE:
```
package main
import (
"github.com/upstash/vector-go"
)
func main() {
index := vector.NewIndex("UPSTASH_VECTOR_REST_URL", "UPSTASH_VECTOR_REST_TOKEN")
index.Range(vector.Range{
Cursor: "0",
Limit: 3,
IncludeMetadata: true,
})
}
```
----------------------------------------
TITLE: Fetching Vectors by ID in Upstash Vector with TypeScript
DESCRIPTION: Basic example of fetching vectors by their IDs. The command returns an array of vector objects matching the requested IDs.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/ts/commands/fetch.mdx#2025-04-11_snippet_0
LANGUAGE: typescript
CODE:
```
await index.fetch(["2", "3"]);
// [{ id: "2" }, { id: "3" }]
```
----------------------------------------
TITLE: Using Namespaces with Upstash Vector in PHP
DESCRIPTION: This PHP example shows how to use namespaces in Upstash Vector. It creates an index instance, defines a namespace called 'ns', and performs upsert and query operations specifically within that namespace.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/namespaces.mdx#2025-04-11_snippet_3
LANGUAGE: php
CODE:
```
use Upstash\Vector\Index;
use Upstash\Vector\VectorUpsert;
use Upstash\Vector\VectorQuery;
$index = new Index(
url: 'UPSTASH_VECTOR_REST_URL',
token: 'UPSTASH_VECTOR_REST_TOKEN',
);
$namespace = $index->namespace('ns');
$namespace->upsert(new VectorUpsert(
id: 'id-0',
vector: [0.9215, 0.3897],
));
$namespace->query(new VectorQuery(
vector: [0.9215, 0.3897],
topK: 5,
));
```
----------------------------------------
TITLE: Setting Up Environment Variables for LlamaParse and Upstash Vector
DESCRIPTION: This snippet shows the content of a .env file containing the required environment variables for Upstash Vector and LlamaParse API access.
SOURCE: https://github.com/upstash/docs/blob/main/vector/integrations/llamaparse.mdx#2025-04-11_snippet_1
LANGUAGE: plaintext
CODE:
```
UPSTASH_VECTOR_REST_URL=your_upstash_url
UPSTASH_VECTOR_REST_TOKEN=your_upstash_token
LLAMA_CLOUD_API_KEY=your_llama_cloud_api_key
```
----------------------------------------
TITLE: Initializing Upstash Vector client using environment variables
DESCRIPTION: Creating a new Index instance that automatically uses the configuration from environment variables.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/ts/getting-started.mdx#2025-04-11_snippet_3
LANGUAGE: typescript
CODE:
```
import { Index } from "@upstash/vector";
const index = new Index();
```
----------------------------------------
TITLE: Querying Vectors with Metadata using curl
DESCRIPTION: Example showing how to query vectors and include their metadata in the response using curl. The request sends a vector to match and specifies to include metadata in the response.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/metadata.mdx#2025-04-11_snippet_9
LANGUAGE: shell
CODE:
```
curl $UPSTASH_VECTOR_REST_URL/query \
-H "Authorization: Bearer $UPSTASH_VECTOR_REST_TOKEN" \
-d '{
"vector":[0.9215,0.3897],
"topK" : 5,
"includeMetadata": true
}'
```
----------------------------------------
TITLE: Accessing Namespace Information Properties in PHP
DESCRIPTION: This snippet shows how to access properties of the NamespaceInfo object returned by the getNamespaceInfo() method. It includes accessing the vector count and pending vector count for a specific namespace.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/php/commands/info.mdx#2025-04-11_snippet_3
LANGUAGE: php
CODE:
```
// To know the number of vectors ready to query.
$myNamespaceInfo->vectorCount;
// To know the number of vectors that are getting indexed.
$myNamespaceInfo->pendingVectorCount;
```
----------------------------------------
TITLE: Retrieving Vector Range with Metadata in PHP
DESCRIPTION: Example showing how to retrieve a range of vectors with their metadata in PHP. The range operation retrieves up to 3 vectors with their associated metadata.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/metadata.mdx#2025-04-11_snippet_19
LANGUAGE: php
CODE:
```
use Upstash\Vector\Index;
use Upstash\Vector\VectorRange;
$index = new Index(
url: 'UPSTASH_VECTOR_REST_URL',
token: 'UPSTASH_VECTOR_REST_TOKEN',
);
$index->range(new VectorRange(
limit: 3,
includeMetadata: true,
));
```
----------------------------------------
TITLE: Upserting Multiple Vectors in Upstash Vector Database
DESCRIPTION: This example shows how to upsert multiple vectors in a single operation. It demonstrates upserting a simple vector with just ID and vector data, along with a more complete vector that includes metadata.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/ts/commands/upsert.mdx#2025-04-11_snippet_1
LANGUAGE: typescript
CODE:
```
await index.upsert([
{
id: "6789",
vector: [0.6, 0.7, 0.8, 0.9, 0.9],
},
{
id: "1234",
vector: [0.1, 0.2, 0.3, 0.4, 0.5],
metadata: {
title: "Lord of The Rings",
genre: "drama",
category: "classic",
},
},
]);
```
----------------------------------------
TITLE: Querying with Metadata Filter in PHP
DESCRIPTION: Example of how to perform a vector similarity search with metadata filtering using the Upstash Vector PHP client. The query includes a vector, filter condition, top-k limit, and metadata inclusion.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/filtering.mdx#2025-04-11_snippet_4
LANGUAGE: php
CODE:
```
use Upstash\Vector\Index;
use Upstash\Vector\VectorQuery;
$index = new Index(
url: 'UPSTASH_VECTOR_REST_URL',
token: 'UPSTASH_VECTOR_REST_TOKEN',
);
$index->query(new VectorQuery(
vector: [0.9215, 0.3897],
topK: 5,
includeMetadata: true,
filter: "population >= 1000000 AND geography.continent = 'Asia'",
));
```
----------------------------------------
TITLE: Deleting a Namespace in Go
DESCRIPTION: This Go code shows how to delete a namespace in Upstash Vector. It creates an index instance, gets a reference to the 'ns' namespace, and calls DeleteNamespace() to remove it.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/namespaces.mdx#2025-04-11_snippet_7
LANGUAGE: go
CODE:
```
package main
import (
"github.com/upstash/vector-go"
)
func main() {
index := vector.NewIndex("UPSTASH_VECTOR_REST_URL", "UPSTASH_VECTOR_REST_TOKEN")
namespace := index.Namespace("ns")
namespace.DeleteNamespace()
}
```
----------------------------------------
TITLE: Server Action Implementation for Resource Creation
DESCRIPTION: Server-side action implementation for creating and upserting new resources with input validation using Zod.
SOURCE: https://github.com/upstash/docs/blob/main/vector/integrations/ai-sdk.mdx#2025-04-11_snippet_4
LANGUAGE: typescript
CODE:
```
'use server'
import { z } from 'zod'
import { upsertEmbeddings } from '@/lib/ai/upstashVector'
const NewResourceSchema = z.object({
content: z.string().min(1),
})
export async function createResource(input: { content: string }) {
const { content } = NewResourceSchema.parse(input)
const resourceId = crypto.randomUUID()
await upsertEmbeddings(resourceId, content)
return `Resource ${resourceId} created and embedded.`
}
```
----------------------------------------
TITLE: Installing Upstash Vector SDK with pip
DESCRIPTION: Command to install the upstash-vector Python SDK using pip package manager. This is the first step to start using the SDK in your project.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/py/gettingstarted.mdx#2025-04-11_snippet_0
LANGUAGE: bash
CODE:
```
pip install upstash-vector
```
----------------------------------------
TITLE: Deleting Vectors by Metadata Filter with Namespaces in PHP
DESCRIPTION: Shows how to delete vectors based on metadata filters from a specific namespace. This combines the namespace() method with the VectorDeleteByMetadataFilter class.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/php/commands/delete-vectors.mdx#2025-04-11_snippet_5
LANGUAGE: php
CODE:
```
use Upstash\Vector\Index;
use Upstash\Vector\VectorDeleteByMetadataFilter;
$index = new Index(
url: "",
token: "",
);
$index->namespace('my-namespace')->delete(new VectorDeleteByMetadataFilter(
filter: 'salary > 1000',
));
```
----------------------------------------
TITLE: Retrieving Vector Range with Metadata in JavaScript
DESCRIPTION: Example showing how to retrieve a range of vectors with their metadata in JavaScript. The range query returns vectors starting from the specified cursor with a limit of 3 records.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/metadata.mdx#2025-04-11_snippet_17
LANGUAGE: javascript
CODE:
```
import { Index } from "@upstash/vector"
const index = new Index({
url: "UPSTASH_VECTOR_REST_URL",
token: "UPSTASH_VECTOR_REST_TOKEN",
})
await index.range({
cursor: "0",
limit: 3,
includeMetadata: true,
})
```
----------------------------------------
TITLE: Accessing Index Information Properties in PHP
DESCRIPTION: This snippet shows how to access various properties of the IndexInfo object returned by the getInfo() method. It includes accessing vector count, pending vector count, index size, dimension, similarity function, and namespace information.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/php/commands/info.mdx#2025-04-11_snippet_1
LANGUAGE: php
CODE:
```
// To know the number of vectors ready to query.
$info->vectorCount;
// To know the number of vectors that are getting indexed.
$info->pendingVectorCount;
// To know the size of the index in bytes.
$info->indexSize;
// To know the dimensions of your vector index.
$info->dimension;
// To know which similarity function is being used.
$info->similarityFunction;
// To get information about a specific index you can (More on next section):
$namespaceInfo = $info->namespace('my-namespace');
```
----------------------------------------
TITLE: Patching Metadata in Upstash Vector Using JSON Merge Patch Algorithm
DESCRIPTION: This example shows how to patch metadata in Upstash Vector database using the JSON Merge Patch algorithm. This method allows updating existing fields, deleting fields by setting them to None, and adding new fields, all in one operation.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/py/example_calls/update.mdx#2025-04-11_snippet_1
LANGUAGE: python
CODE:
```
from upstash_vector import Index
from upstash_vector.types import MetadataUpdateMode
index = Index.from_env()
updated = index.update(
id="id2",
metadata={
"existing-field": "new-value",
"existing-field-to-delete": None,
"new-field": "new-value",
},
metadata_update_mode=MetadataUpdateMode.PATCH,
)
print(updated)
```
----------------------------------------
TITLE: Upserting Raw Text Data
DESCRIPTION: Demonstrates how to upsert raw text data which automatically sets the data field. This is useful for storing textual context alongside vector embeddings.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/metadata.mdx#2025-04-11_snippet_23
LANGUAGE: python
CODE:
```
from upstash_vector import Index
index = Index(
url="UPSTASH_VECTOR_REST_URL",
token="UPSTASH_VECTOR_REST_TOKEN",
)
index.upsert(
[
{
"id": "id-2",
"data": "Upstash is a serverless data platform.",
},
],
)
```
LANGUAGE: javascript
CODE:
```
import { Index } from "@upstash/vector"
const index = new Index({
url: "UPSTASH_VECTOR_REST_URL",
token: "UPSTASH_VECTOR_REST_TOKEN",
})
await index.upsert([
{
id: "id-2",
data: "Upstash is a serverless data platform.",
}
])
```
LANGUAGE: php
CODE:
```
use Upstash\Vector\Index;
use Upstash\Vector\DataUpsert;
$index = new Index(
url: 'UPSTASH_VECTOR_REST_URL',
token: 'UPSTASH_VECTOR_REST_TOKEN',
);
$index->upsertData(new DataUpsert(
id: 'id-0',
data: 'Upstash is a serverless data platform.',
));
```
LANGUAGE: shell
CODE:
```
curl $UPSTASH_VECTOR_REST_URL/upsert-data \
-X POST \
-H "Authorization: Bearer $UPSTASH_VECTOR_REST_TOKEN" \
-d '{
"id": "id-0",
"data": "Upstash is a serverless data platform."
}'
```
----------------------------------------
TITLE: Upserting Text Data with Embedding Models in Go
DESCRIPTION: Shows how to upsert raw text data into Upstash Vector using Go. The text will be automatically converted to vector embeddings by the selected model.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/embeddingmodels.mdx#2025-04-11_snippet_2
LANGUAGE: go
CODE:
```
package main
import (
"github.com/upstash/vector-go"
)
func main() {
index := vector.NewIndex("UPSTASH_VECTOR_REST_URL", "UPSTASH_VECTOR_REST_TOKEN")
index.UpsertData(vector.UpsertData{
Id: "id-0",
Data: "Upstash is a serverless data platform.",
Metadata: map[string]any{"field": "value"},
})
}
```
----------------------------------------
TITLE: Fetching Index Information with Upstash Vector PHP SDK
DESCRIPTION: This snippet demonstrates how to create an Index instance and use the getInfo() method to retrieve information about the vector index. It requires the Upstash Vector REST URL and token.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/php/commands/info.mdx#2025-04-11_snippet_0
LANGUAGE: php
CODE:
```
use Upstash\Vector\Index;
$index = new Index(
url: "",
token: "",
);
$info = $index->getInfo();
```
----------------------------------------
TITLE: Starting a Resumable Query in Go with Upstash Vector
DESCRIPTION: Initializes a resumable vector similarity search query in Go that returns the first batch of results along with a handle for fetching more results later. The example includes metadata in the results and requests the top 2 most similar vectors.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/resumablequery.mdx#2025-04-11_snippet_2
LANGUAGE: go
CODE:
```
package main
import (
"fmt"
"log"
"github.com/upstash/vector-go"
)
func main() {
index := vector.NewIndex(
"UPSTASH_VECTOR_REST_URL",
"UPSTASH_VECTOR_REST_TOKEN",
)
scores, handle, err := index.ResumableQuery(vector.ResumableQuery{
Vector: []float32{0.1, 0.2},
TopK: 2,
IncludeMetadata: true,
})
if err != nil {
log.Fatal(err)
}
defer handle.Close()
// first batch of the results
for _, score := range scores {
fmt.Printf("%+v\n", score)
}
}
```
----------------------------------------
TITLE: Retrieving Vectors with Improved Type Handling in TypeScript
DESCRIPTION: This snippet demonstrates how to use the range method with improved TypeScript type handling. It defines a custom Metadata type and uses it as a generic parameter for better type inference when working with the retrieved data.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/ts/commands/range.mdx#2025-04-11_snippet_2
LANGUAGE: typescript
CODE:
```
type Metadata = {
title: string;
genre: "sci-fi" | "fantasy" | "horror" | "action";
};
const responseRange = await index.range({
cursor: 0,
limit: 2,
includeMetadata: true,
});
if (responseRange[0].metadata) {
// Since we passed the Metadata type parameter above,
// we can interact with metadata fields without having to
// do any typecasting.
const { title, genre } = results[0].metadata;
console.log(`The best match in fantasy was ${title}`);
}
```
----------------------------------------
TITLE: Deleting a Namespace in JavaScript
DESCRIPTION: This JavaScript code demonstrates how to delete a namespace in Upstash Vector. It creates an index instance and uses the deleteNamespace method to remove the 'ns' namespace.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/namespaces.mdx#2025-04-11_snippet_6
LANGUAGE: javascript
CODE:
```
import { Index } from "@upstash/vector"
const index = new Index({
url: "UPSTASH_VECTOR_REST_URL",
token: "UPSTASH_VECTOR_REST_TOKEN",
})
await index.deleteNamespace("ns")
```
----------------------------------------
TITLE: Updating Vector Metadata Using cURL
DESCRIPTION: This example demonstrates how to update a vector's metadata in the default namespace using the Upstash Vector REST API. The request includes the vector ID and new metadata containing a link property.
SOURCE: https://github.com/upstash/docs/blob/main/vector/api/endpoints/update.mdx#2025-04-11_snippet_0
LANGUAGE: sh
CODE:
```
curl $UPSTASH_VECTOR_REST_URL/update \
-X POST \
-H "Authorization: Bearer $UPSTASH_VECTOR_REST_TOKEN" \
-d '{ "id": "id-1", "metadata": { "link": "upstash.com" } }'
```
----------------------------------------
TITLE: Deleting Vectors by ID Prefix in Python
DESCRIPTION: Example demonstrating how to delete all vectors whose IDs start with a specified prefix. This is useful for batch deletions of related vectors.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/py/example_calls/delete.mdx#2025-04-11_snippet_4
LANGUAGE: python
CODE:
```
index.delete(prefix="id-")
```
----------------------------------------
TITLE: Implementing Custom Reranking for Hybrid Index in Go
DESCRIPTION: This Go code snippet illustrates how to implement custom reranking for a hybrid index. It performs separate queries for dense and sparse components, allowing for custom reranking of the results.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/hybridindexes.mdx#2025-04-11_snippet_16
LANGUAGE: go
CODE:
```
package main
import (
"github.com/upstash/vector-go"
)
func main() {
index := vector.NewIndex(
"UPSTASH_VECTOR_REST_URL",
"UPSTASH_VECTOR_REST_TOKEN",
)
denseScores, err := index.Query(vector.Query{
Vector: []float32{0.5, 0.4},
})
sparseScores, err := index.Query(vector.Query{
SparseVector: &vector.SparseVector{
Indices: []int32{3, 5},
Values: []float32{0.3, 05},
},
})
// Rerank dense and sparse results as you like here
}
```
----------------------------------------
TITLE: Querying Upstash Vector Namespaces using cURL
DESCRIPTION: This cURL command demonstrates how to list the namespaces of an Upstash Vector index. It requires the UPSTASH_VECTOR_REST_URL and UPSTASH_VECTOR_REST_TOKEN environment variables to be set.
SOURCE: https://github.com/upstash/docs/blob/main/vector/api/endpoints/list-namespaces.mdx#2025-04-11_snippet_0
LANGUAGE: sh
CODE:
```
curl $UPSTASH_VECTOR_REST_URL/list-namespaces \
-H "Authorization: Bearer $UPSTASH_VECTOR_REST_TOKEN"
```
----------------------------------------
TITLE: Fetching Vectors by ID Prefix in Upstash Vector
DESCRIPTION: Example demonstrating how to fetch all vectors with IDs that start with a specific prefix. This is useful for retrieving groups of related vectors, though for larger datasets the paginated 'range' command is recommended to prevent timeouts.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/py/example_calls/fetch.mdx#2025-04-11_snippet_3
LANGUAGE: python
CODE:
```
index.fetch(prefix="id-")
```
----------------------------------------
TITLE: Setting Environment Variables for Upstash Vector Client
DESCRIPTION: Bash commands to set the required environment variables for configuring the Upstash Vector client.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/ts/overview-backup.mdx#2025-04-11_snippet_1
LANGUAGE: bash
CODE:
```
UPSTASH_VECTOR_REST_URL="your_rest_url"
UPSTASH_VECTOR_REST_TOKEN="your_rest_token"
```
----------------------------------------
TITLE: Initializing Upstash Vector client with configuration object
DESCRIPTION: Creating a new Index instance by explicitly providing configuration parameters, useful when working with multiple projects.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/ts/getting-started.mdx#2025-04-11_snippet_4
LANGUAGE: typescript
CODE:
```
import { Index } from "@upstash/vector";
const index = new Index({
url: "",
token: "",
});
```
----------------------------------------
TITLE: Fetching a Vector from a Specific Namespace in Upstash Vector
DESCRIPTION: Example showing how to fetch a vector from a specific namespace in Upstash Vector. When no namespace is specified, the default namespace is used.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/py/example_calls/fetch.mdx#2025-04-11_snippet_2
LANGUAGE: python
CODE:
```
index.fetch("id-4", namespace="ns")
```
----------------------------------------
TITLE: Deleting Vectors by Metadata Filter in PHP
DESCRIPTION: Demonstrates how to delete vectors based on their metadata using the VectorDeleteByMetadataFilter class. The example deletes vectors where the salary metadata value is greater than 1000.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/php/commands/delete-vectors.mdx#2025-04-11_snippet_4
LANGUAGE: php
CODE:
```
use Upstash\Vector\Index;
use Upstash\Vector\VectorDeleteByMetadataFilter;
$index = new Index(
url: "",
token: "",
);
$index->delete(new VectorDeleteByMetadataFilter(
filter: 'salary > 1000',
));
```
----------------------------------------
TITLE: Performing Text-Based Similarity Search
DESCRIPTION: Implementation of semantic search using text query input
SOURCE: https://github.com/upstash/docs/blob/main/vector/tutorials/huggingface-embeddings.mdx#2025-04-11_snippet_4
LANGUAGE: python
CODE:
```
# Querying Vectors using a text query\nquery_text = "What are the effects of global warming?"\nquery_embedding = embeddings.embed_query(query_text)\n\n# Perform similarity search with the query text\nresult_text_query = vector_store.similarity_search(\n query=query_text,\n k=5 # Number of top results to return\n)\n\nprint("Results for text-based similarity search:")\nfor res in result_text_query:\n print(res.page_content)
```
----------------------------------------
TITLE: Updating Metadata for Data-based Vectors in Upstash Vector Database
DESCRIPTION: This example demonstrates initially upserting a data item with metadata and then updating just the metadata. This allows changing associated information without modifying the underlying vector or regenerating embeddings.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/ts/commands/upsert.mdx#2025-04-11_snippet_6
LANGUAGE: typescript
CODE:
```
await index.upsert({
id: "1234",
data: "Upstash product"
metadata: {
title: "Redis"
}
})
await index.upsert({
id: "1234",
metadata: {
title: "QStash"
}
})
```
----------------------------------------
TITLE: Installing Upstash Vector Node.js Client
DESCRIPTION: Commands to install the Upstash Vector Node.js client using npm or pnpm package managers.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/ts/overview-backup.mdx#2025-04-11_snippet_0
LANGUAGE: bash
CODE:
```
npm install @upstash/vector
pnpm add @upstash/vector
```
----------------------------------------
TITLE: Weighting Query Values with IDF in Upstash Vector (cURL)
DESCRIPTION: This snippet shows how to use Inverse Document Frequency (IDF) weighting when querying text data in Upstash Vector using cURL. It demonstrates sending a POST request with the weightingStrategy parameter set to IDF.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/sparseindexes.mdx#2025-04-11_snippet_25
LANGUAGE: shell
CODE:
```
curl $UPSTASH_VECTOR_REST_URL/query-data \
-H "Authorization: Bearer $UPSTASH_VECTOR_REST_TOKEN" \
-d '{"data": "Upstash Vector", "topK": 5, "weightingStrategy": "IDF"}'
```
----------------------------------------
TITLE: Deleting a Namespace with curl
DESCRIPTION: This curl example shows how to delete a namespace in Upstash Vector using a DELETE request to the delete-namespace endpoint, specifying the namespace 'ns' in the URL path.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/namespaces.mdx#2025-04-11_snippet_9
LANGUAGE: shell
CODE:
```
curl $UPSTASH_VECTOR_REST_URL/delete-namespace/ns \
-X DELETE \
-H "Authorization: Bearer $UPSTASH_VECTOR_REST_TOKEN"
```
----------------------------------------
TITLE: Querying Upstash Vector Index using Go
DESCRIPTION: Code for performing a similarity search in an Upstash Vector Index using the Go SDK. It demonstrates how to query the index with a vector, limit results, and include metadata in the response.
SOURCE: https://github.com/upstash/docs/blob/main/vector/overall/getstarted.mdx#2025-04-11_snippet_7
LANGUAGE: go
CODE:
```
import "github.com/upstash/vector-go"
func main() {
index := vector.NewIndex("UPSTASH_VECTOR_REST_URL", "UPSTASH_VECTOR_REST_TOKEN")
index.Query(vector.Query{
Vector: []float32{0.6, 0.8},
TopK: 3,
IncludeMetadata: true,
})
}
```
----------------------------------------
TITLE: Fetching Vectors by ID with Namespace in PHP using Upstash Vector
DESCRIPTION: This code shows how to fetch vectors from a specific namespace in an Upstash Vector database using their IDs. It utilizes the namespace() method before calling fetch(), allowing for organized data retrieval within a designated namespace.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/php/commands/fetch.mdx#2025-04-11_snippet_1
LANGUAGE: php
CODE:
```
use Upstash\Vector\Index;
use Upstash\Vector\VectorFetch;
$index = new Index(
url: "",
token: "",
);
$results = $index->namespace('my-namespace')->fetch(new VectorFetch(
ids: ['1', '2'],
includeMetadata: true, // (optional) if true the fetch results will contain metadata.
includeVectors: true, // (optional) if true the fetch results will contain the indexed vectors.
includeData: true, // (optional) if true the fetch results will contain the string data.
));
```
----------------------------------------
TITLE: Resetting Default Namespace in Vector Index - TypeScript
DESCRIPTION: Demonstrates how to reset the default namespace in a vector index. Returns 'Successful' on successful reset operation.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/ts/commands/reset.mdx#2025-04-11_snippet_0
LANGUAGE: typescript
CODE:
```
const responseReset = await index.reset();
// 'Successful'
```
----------------------------------------
TITLE: Custom Embedding Model Implementation with OpenAI
DESCRIPTION: Implementation using OpenAI's text-embedding-ada-002 model for generating and managing vector embeddings.
SOURCE: https://github.com/upstash/docs/blob/main/vector/integrations/ai-sdk.mdx#2025-04-11_snippet_3
LANGUAGE: typescript
CODE:
```
import { Index } from '@upstash/vector'
import { embed, embedMany } from 'ai'
import { openai } from '@ai-sdk/openai'
const index = new Index({
url: process.env.UPSTASH_VECTOR_REST_URL!,
token: process.env.UPSTASH_VECTOR_REST_TOKEN!,
})
function generateChunks(input: string): string[] {
return input
.trim()
.split('.')
.filter(i => i !== '')
}
const embeddingModel = openai.embedding('text-embedding-ada-002')
async function generateEmbedding(value: string): Promise {
const input = value.replaceAll('\\n', ' ')
const { embedding } = await embed({
model: embeddingModel,
value: input,
})
return embedding
}
async function generateEmbeddings(
value: string,
): Promise> {
const chunks = generateChunks(value)
const { embeddings } = await embedMany({
model: embeddingModel,
values: chunks,
})
return embeddings.map((vector, i) => ({
content: chunks[i],
embedding: vector,
}))
}
export async function upsertEmbeddings(resourceId: string, content: string) {
const chunkEmbeddings = await generateEmbeddings(content)
const toUpsert = chunkEmbeddings.map((chunk, i) => ({
id: `${resourceId}-${i}`,
vector: chunk.embedding,
metadata: {
resourceId,
content: chunk.content,
},
}))
await index.upsert(toUpsert)
}
export async function findRelevantContent(query: string, k = 4) {
const userEmbedding = await generateEmbedding(query)
const result = await index.query({
vector: userEmbedding,
topK: k,
includeMetadata: true,
})
return result
}
```
----------------------------------------
TITLE: Upserting Multiple Vectors Using Curl
DESCRIPTION: Example of upserting multiple vectors with metadata using curl to the default namespace. Demonstrates how to send array of vectors with IDs, data, and metadata.
SOURCE: https://github.com/upstash/docs/blob/main/vector/api/endpoints/upsert-data.mdx#2025-04-11_snippet_0
LANGUAGE: sh
CODE:
```
curl $UPSTASH_VECTOR_REST_URL/upsert-data \
-X POST \
-H "Authorization: Bearer $UPSTASH_VECTOR_REST_TOKEN" \
-d '[
{ "id": "id-0", "data": "Upstash is a serverless data platform.", "metadata": { "link": "upstash.com" } },
{ "id": "id-1", "data": "Upstash Vector is a serverless vector database." }
]'
```
----------------------------------------
TITLE: Using Namespaces with Upstash Vector in Go
DESCRIPTION: This Go example demonstrates how to use namespaces in Upstash Vector. It creates an index, defines a namespace called 'ns', and performs upsert and query operations within that specific namespace.
SOURCE: https://github.com/upstash/docs/blob/main/vector/features/namespaces.mdx#2025-04-11_snippet_2
LANGUAGE: go
CODE:
```
package main
import (
"github.com/upstash/vector-go"
)
func main() {
index := vector.NewIndex("UPSTASH_VECTOR_REST_URL", "UPSTASH_VECTOR_REST_TOKEN")
namespace := index.Namespace("ns")
namespace.Upsert(vector.Upsert{
Id: "id-0",
Vector: []float32{0.9215, 0.3897},
})
namespace.Query(vector.Query{
Vector: []float32{0.9215, 0.3897},
TopK: 5,
})
}
```
----------------------------------------
TITLE: Installing Upstash Vector SDK via pnpm
DESCRIPTION: Command to install @upstash/vector using pnpm package manager.
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/ts/getting-started.mdx#2025-04-11_snippet_1
LANGUAGE: shell
CODE:
```
pnpm add @upstash/vector
```
----------------------------------------
TITLE: JSON Response Structure for Fetching Vectors in Upstash Vector Database
DESCRIPTION: This snippet illustrates the JSON response structure when fetching vectors. It shows the format of the result array containing vector objects with their IDs and optional metadata.
SOURCE: https://github.com/upstash/docs/blob/main/vector/api/endpoints/fetch.mdx#2025-04-11_snippet_2
LANGUAGE: json
CODE:
```
{
"result": [
{
"id": "id-0",
"metadata": {
"link": "upstash.com"
}
},
{
"id": "id-1"
}
]
}
```
----------------------------------------
TITLE: Deleting Vectors Using Curl - Custom Namespace
DESCRIPTION: Example of deleting vectors using curl command with vector IDs in a custom namespace 'ns'. Requires authentication via bearer token.
SOURCE: https://github.com/upstash/docs/blob/main/vector/api/endpoints/delete.mdx#2025-04-11_snippet_1
LANGUAGE: sh
CODE:
```
curl $UPSTASH_VECTOR_REST_URL/delete/ns \
-X DELETE \
-H "Authorization: Bearer $UPSTASH_VECTOR_REST_TOKEN" \
-d '{ "ids": [ "id-0", "id-1" ] }'
```
----------------------------------------
TITLE: Deleting Vectors by ID with Namespaces in PHP
DESCRIPTION: Shows how to delete specific vectors by their IDs from a specific namespace in an Upstash Vector database. This approach uses the namespace() method before calling delete().
SOURCE: https://github.com/upstash/docs/blob/main/vector/sdks/php/commands/delete-vectors.mdx#2025-04-11_snippet_1
LANGUAGE: php
CODE:
```
use Upstash\Vector\Index;
$index = new Index(
url: "",
token: "",
);
$index->namespace('my-namespace')->delete(['1', '2', '3']);
```