How to query Pinecone index
Quick answer
Use the Pinecone Python SDK v3 to query a vector index by initializing the client with
Pinecone(api_key=), accessing your index with pc.Index(name), and calling index.query(vector=[...], top_k=3) to retrieve the nearest vectors. The response contains matches ranked by similarity scores.PREREQUISITES
Python 3.8+Pinecone API keypip install pinecone-client>=3.0
Setup
Install the Pinecone Python SDK v3 and set your API key as an environment variable.
- Run
pip install pinecone-clientto install the SDK. - Export your API key in your shell:
export PINECONE_API_KEY='your_api_key'(Linux/macOS) or set it in your environment variables on Windows.
pip install pinecone-client Step by step
This example demonstrates how to query a Pinecone index for the top 3 nearest vectors to a given query vector.
import os
from pinecone import Pinecone
# Initialize Pinecone client
pc = Pinecone(api_key=os.environ["PINECONE_API_KEY"])
# Connect to your existing index
index = pc.Index("example-index")
# Define a query vector (example 1536-dimensional float vector)
query_vector = [0.1] * 1536
# Query the index for top 3 matches
response = index.query(vector=query_vector, top_k=3)
# Print the matches
for match in response.matches:
print(f"ID: {match.id}, Score: {match.score}") output
ID: vec123, Score: 0.95 ID: vec456, Score: 0.93 ID: vec789, Score: 0.91
Common variations
You can customize queries by changing top_k to retrieve more or fewer results, or add filter parameters to apply metadata-based filtering. Async querying is not supported in the Pinecone SDK v3 currently.
response = index.query(
vector=query_vector,
top_k=5,
filter={"category": "news"}
)
for match in response.matches:
print(f"ID: {match.id}, Score: {match.score}") output
ID: vec234, Score: 0.97 ID: vec567, Score: 0.94 ID: vec890, Score: 0.92 ID: vec345, Score: 0.90 ID: vec678, Score: 0.89
Troubleshooting
- If you get an authentication error, verify your
PINECONE_API_KEYenvironment variable is set correctly. - If the index does not exist, create it first via the Pinecone dashboard or SDK before querying.
- Ensure your query vector dimension matches the index dimension to avoid errors.
Key Takeaways
- Initialize Pinecone client with your API key from environment variables.
- Use
index.query(vector=[...], top_k=)to retrieve nearest vectors efficiently. - Apply metadata filters in queries to narrow down results.
- Ensure vector dimensions match your index schema to avoid errors.
- Check environment variables and index existence if queries fail.