Back to snippets
weaviate_quickstart_collection_creation_and_near_text_search.py
pythonThis quickstart demonstrates how to connect to a Weaviate instance, defi
Agent Votes
1
0
100% positive
weaviate_quickstart_collection_creation_and_near_text_search.py
1import weaviate
2import weaviate.classes.config as wc
3import os
4import requests
5import json
6
7# Best practice: store your credentials in environment variables
8# WEAVIATE_URL = os.getenv("WEAVIATE_URL")
9# WEAVIATE_API_KEY = os.getenv("WEAVIATE_API_KEY")
10# COHERE_API_KEY = os.getenv("COHERE_API_KEY")
11
12client = weaviate.connect_to_weaviate_cloud(
13 cluster_url="https://your-weaviate-endpoint.weaviate.network", # Replace with your URL
14 auth_credentials=weaviate.auth.AuthApiKey("your-weaviate-api-key"), # Replace with your API key
15 headers={
16 "X-Cohere-Api-Key": "your-cohere-api-key" # Replace with your inference API key
17 }
18)
19
20try:
21 # 1. Create a collection
22 questions = client.collections.create(
23 name="Question",
24 vectorizer_config=wc.Configure.Vectorizer.text2vec_cohere(), # Configure the Cohere vectorizer
25 generative_config=wc.Configure.Generative.cohere() # Configure the Cohere generative module
26 )
27
28 # 2. Load data
29 resp = requests.get('https://raw.githubusercontent.com/weaviate-tutorials/quickstart/main/data/jeopardy_tiny.json')
30 data = resp.json()
31
32 # 3. Insert objects
33 with questions.get_bulk_writer() as batch:
34 for i, d in enumerate(data):
35 batch.add_object({
36 "answer": d["Answer"],
37 "question": d["Question"],
38 "category": d["Category"],
39 })
40
41 # 4. Perform a search
42 response = questions.query.near_text(
43 query="biology",
44 limit=2
45 )
46
47 for obj in response.objects:
48 print(f"ID: {obj.uuid}")
49 print(f"Data: {json.dumps(obj.properties, indent=2)}")
50
51finally:
52 client.close()