python --version
pip install pinecone
Set PINECONE_API_KEY env var
Create a Pinecone index, upsert embeddings with metadata, and perform filtered similarity search.
1 import os 2 import random 3 import time 4 from pinecone import Pinecone, ServerlessSpec 5 6 DIM = 384 7 8 pc = Pinecone(api_key=os.environ["PINECONE_API_KEY"]) 9 10 INDEX_NAME = "learn-index" 11 12 # Create index if it doesn't exist 13 if INDEX_NAME not in [idx.name for idx in pc.list_indexes()]: 14 pc.create_index( 15 name=INDEX_NAME, 16 dimension=DIM, 17 metric="cosine", 18 spec=ServerlessSpec(cloud="aws", region="us-east-1"), 19 ) 20 # Wait for index to be ready 21 while not pc.describe_index(INDEX_NAME).status["ready"]: 22 time.sleep(1) 23 24 index = pc.Index(INDEX_NAME) 25 26 def random_vector(dim: int) -> list[float]: 27 v = [random.gauss(0, 1) for _ in range(dim)] 28 norm = sum(x * x for x in v) ** 0.5 29 return [x / norm for x in v] 30 31 categories = ["news", "blog", "research"] 32 33 # Upsert in batches (max 100 per call) 34 vectors = [ 35 { 36 "id": f"doc-{i}", 37 "values": random_vector(DIM), 38 "metadata": { 39 "category": random.choice(categories), 40 "source": f"site-{random.randint(1, 5)}.com", 41 "score": round(random.uniform(0, 1), 3), 42 }, 43 } 44 for i in range(100) 45 ] 46 index.upsert(vectors=vectors, namespace="demo") 47 print("Upserted 100 vectors") 48 49 # Wait for freshness 50 time.sleep(5) 51 52 # Filtered similarity query 53 query_vec = random_vector(DIM) 54 results = index.query( 55 vector=query_vec, 56 top_k=5, 57 filter={"category": {"$eq": "news"}}, 58 include_metadata=True, 59 namespace="demo", 60 ) 61 print("Top 5 'news' matches:") 62 for match in results.matches: 63 print(f" id={match.id}, score={match.score:.4f}, meta={match.metadata}") 64 65 # Fetch by ID 66 fetch_result = index.fetch(ids=["doc-0"], namespace="demo") 67 print(f"Fetched doc-0 metadata: {fetch_result.vectors['doc-0'].metadata}") 68 69 # Delete 70 index.delete(ids=["doc-0", "doc-1"], namespace="demo") 71 print("Deleted doc-0 and doc-1") 72
Sign in to share your feedback and join the discussion.