python --version
pip install weaviate-client
docker run -p 8080:8080 semitechnologies/weaviate
Create a Weaviate collection, insert objects with embeddings, and perform vector and hybrid search.
1 import weaviate 2 import weaviate.classes as wvc 3 import random 4 5 DIM = 384 6 7 def random_vector(dim: int) -> list[float]: 8 v = [random.gauss(0, 1) for _ in range(dim)] 9 norm = sum(x * x for x in v) ** 0.5 10 return [x / norm for x in v] 11 12 # Connect to local Weaviate 13 client = weaviate.connect_to_local() 14 15 try: 16 # Create collection 17 COLLECTION = "Article" 18 if client.collections.exists(COLLECTION): 19 client.collections.delete(COLLECTION) 20 21 articles = client.collections.create( 22 name=COLLECTION, 23 vectorizer_config=wvc.config.Configure.Vectorizer.none(), # We provide our own vectors 24 properties=[ 25 wvc.config.Property(name="title", data_type=wvc.config.DataType.TEXT), 26 wvc.config.Property(name="content", data_type=wvc.config.DataType.TEXT), 27 wvc.config.Property(name="category", data_type=wvc.config.DataType.TEXT), 28 ], 29 ) 30 31 # Batch import 32 categories = ["tech", "health", "finance", "sports"] 33 with articles.batch.dynamic() as batch: 34 for i in range(20): 35 batch.add_object( 36 properties={ 37 "title": f"Article {i}: Understanding topic {i % 5}", 38 "content": f"This article discusses important aspects of topic {i % 5} in detail.", 39 "category": random.choice(categories), 40 }, 41 vector=random_vector(DIM), 42 ) 43 print(f"Imported {articles.aggregate.over_all().total_count} articles") 44 45 # Near-vector search (semantic similarity) 46 query_vec = random_vector(DIM) 47 results = articles.query.near_vector( 48 near_vector=query_vec, 49 limit=3, 50 return_properties=["title", "category"], 51 return_metadata=wvc.query.MetadataQuery(distance=True), 52 ) 53 print("\nNear-vector results:") 54 for obj in results.objects: 55 print(f" {obj.properties['title']} (category: {obj.properties['category']}, dist: {obj.metadata.distance:.4f})") 56 57 # Filtered search 58 filtered_results = articles.query.near_vector( 59 near_vector=query_vec, 60 limit=3, 61 filters=wvc.query.Filter.by_property("category").equal("tech"), 62 return_properties=["title", "category"], 63 ) 64 print("\nFiltered (tech only):") 65 for obj in filtered_results.objects: 66 print(f" {obj.properties['title']}") 67 68 finally: 69 client.close() 70
Sign in to share your feedback and join the discussion.