pythonintermediate

Weaviate Vector Store in Python

Store, index, and perform semantic search on documents using the Weaviate Python client.

python
import weaviate
from weaviate.classes.config import Configure, Property, DataType
from weaviate.classes.query import MetadataQuery

client = weaviate.connect_to_local()

if not client.collections.exists('Article'):
    client.collections.create(
        'Article',
        vectorizer_config=Configure.Vectorizer.text2vec_openai(),
        properties=[Property(name='content', data_type=DataType.TEXT), Property(name='title', data_type=DataType.TEXT)],
    )

collection = client.collections.get('Article')
collection.data.insert_many([
    {'content': 'Python is great for AI.', 'title': 'Python AI'},
    {'content': 'LLMs power modern chatbots.', 'title': 'LLMs'},
])

results = collection.query.near_text(query='artificial intelligence', limit=2, return_metadata=MetadataQuery(distance=True))
for obj in results.objects:
    print(obj.properties, obj.metadata.distance)

client.close()

Use Cases

  • semantic search
  • knowledge bases
  • vector storage

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.