Importing Data Objects
Learn to efficiently import and manage data objects into your Weaviate instance, including their associated vectors.
Importing Data Objects is a free Vector Databases: Pinecone, Weaviate & pgvector lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Vector Databases: Pinecone, Weaviate & pgvector learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Importing Data to Weaviate
Welcome! In this lesson, you'll learn how to get your valuable data into your Weaviate instance. This is a crucial step for performing semantic searches and leveraging Weaviate's powerful capabilities.
We'll cover how to add individual data objects and, more importantly, how to efficiently import large datasets using batch operations, including handling custom vectors.
Setting Up the Weaviate Client
Before you can import data, you need to establish a connection to your Weaviate instance using its Python client. This client acts as your primary interface for interacting with the database.
Run the code below to see how to connect to a local Weaviate instance.
import weaviate
def main():
# Connect to a local Weaviate instance
# For a cloud instance, you'd use weaviate.connect_to_wcs(...)
client = weaviate.connect_to_local()
if client.is_connected():
print("Weaviate client connected successfully!")
else:
print("Failed to connect to Weaviate.")
client.close() # Always close the connection
if __name__ == "__main__":
main()Understanding Weaviate Objects
In Weaviate, your data is stored as data objects. Each object belongs to a specific collection (similar to a table or class) and has:
- Properties: Key-value pairs describing your data (e.g., a 'title' or 'content' for an article).
- Vector: A numerical representation (embedding) of the object's meaning, used for similarity searches.
Weaviate can generate these vectors for you, or you can provide your own.
Adding a Single Data Object
The simplest way to add data is by creating one object at a time. This is useful for small amounts of data or when testing. Weaviate will automatically generate an embedding for your object based on its properties.
This example assumes you have an 'Article' collection defined (from the previous lesson).
import weaviate
def main():
client = weaviate.connect_to_local()
if not client.is_connected():
print("Connection error. Exiting.")
return
article_obj = {
"title": "Introduction to Embeddings",
"content": "Embeddings convert data into numerical vectors for AI tasks."
}
try:
data_id = client.data_object.create(
properties=article_obj,
collection="Article" # Must match your schema
)
print(f"Article object created with ID: {data_id}")
except Exception as e:
print(f"Error creating object: {e}")
finally:
client.close()
if __name__ == "__main__":
main()Including Custom Vectors
Often, you'll want to use embeddings pre-generated by your own models (e.g., from an OpenAI API call). You can provide these custom vectors when creating an object.
The example uses a placeholder vector. In a real application, this would be a high-dimensional vector from an embedding model.
import weaviate
def main():
client = weaviate.connect_to_local()
if not client.is_connected():
print("Connection error. Exiting.")
return
article_obj = {
"title": "Advanced RAG Techniques",
"content": "RAG systems can be enhanced with query transformations."
}
# Example custom vector (dimensions must match your collection config)
custom_vector = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8]
try:
data_id = client.data_object.create(
properties=article_obj,
collection="Article",
vector=custom_vector # Provide your pre-generated vector
)
print(f"Article object created with ID: {data_id}")
except Exception as e:
print(f"Error creating object: {e}")
finally:
client.close()
if __name__ == "__main__":
main()Efficient Batch Imports
For large datasets, importing objects one by one is inefficient due to network overhead. Weaviate's batch import functionality allows you to send multiple objects in a single request, drastically improving performance.
This method is highly recommended for production applications and large-scale data ingestion.
Implementing Basic Batch Import
Weaviate's client provides a convenient context manager for batching. You add objects to the batch, and the client handles sending them efficiently.
In this example, Weaviate will generate the vectors for each article in the batch.
import weaviate
def main():
client = weaviate.connect_to_local()
if not client.is_connected():
print("Connection error. Exiting.")
return
articles_to_import = [
{"title": "Vector DBs Explained", "content": "Store and search vectors."},
{"title": "Pinecone vs. Weaviate", "content": "Comparing vector databases."},
{"title": "Introduction to pgvector", "content": "Vectors in PostgreSQL."}
]
try:
with client.batch as batch:
for article in articles_to_import:
batch.add_object(
properties=article,
collection="Article"
)
print(f"Successfully added {len(articles_to_import)} objects in batch.")
except Exception as e:
print(f"Error during batch import: {e}")
finally:
client.close()
if __name__ == "__main__":
main()Batching with Pre-Generated Vectors
Just like with single object imports, you can provide custom vectors for each object when performing a batch import. This is common when you've already processed your data through an embedding model.
Ensure the vector dimensions match your collection's configuration.
import weaviate
def main():
client = weaviate.connect_to_local()
if not client.is_connected():
print("Connection error. Exiting.")
return
data_with_vectors = [
{
"properties": {"title": "AI in Healthcare", "content": "LLMs for medical research."},
"vector": [0.11, 0.22, 0.33, 0.44, 0.55, 0.66, 0.77, 0.88]
},
{
"properties": {"title": "Future of Robotics", "content": "Automation and ML."},
"vector": [0.88, 0.77, 0.66, 0.55, 0.44, 0.33, 0.22, 0.11]
}
]
try:
with client.batch as batch:
for item in data_with_vectors:
batch.add_object(
properties=item["properties"],
collection="Article",
vector=item["vector"]
)
print(f"Successfully added {len(data_with_vectors)} objects with vectors in batch.")
except Exception as e:
print(f"Error during batch import with vectors: {e}")
finally:
client.close()
if __name__ == "__main__":
main()Import Best Practices
To optimize your data import process:
- Batch Size: Experiment with
batch_size(e.g., 64, 128, 256) for optimal throughput based on your network and Weaviate instance. - Error Handling: Implement robust error handling and retry mechanisms, especially for large imports that might face transient network issues.
- Pre-process Data: Clean and structure your data before importing to ensure consistency with your Weaviate schema.
- Asynchronous Imports: For very large datasets, consider asynchronous batching for even greater efficiency.
Check Your Understanding
Which of these are benefits of using Weaviate's batch import functionality compared to importing objects one by one?
Recap: Importing Weaviate Data
Great job! You've learned the essentials of getting your data into Weaviate:
- How to connect to your Weaviate instance using the client.
- The structure of a Weaviate data object, including properties and vectors.
- Adding individual data objects, with or without custom vectors.
- The importance and implementation of efficient batch imports for large datasets.
Now you're ready to populate your Weaviate collections with your own data!
Frequently asked questions
Is the “Importing Data Objects” lesson free?
Yes — the full text of “Importing Data Objects” is free to read here on the web, and the Vector Databases: Pinecone, Weaviate & pgvector course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Vector Databases: Pinecone, Weaviate & pgvector course, upgrade to CoddyKit PRO.
What will I learn in “Importing Data Objects”?
Learn to efficiently import and manage data objects into your Weaviate instance, including their associated vectors. You practise Vector Databases: Pinecone, Weaviate & pgvector with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Vector Databases: Pinecone, Weaviate & pgvector?
No prior experience is required. Vector Databases: Pinecone, Weaviate & pgvector on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Importing Data Objects” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Vector Databases: Pinecone, Weaviate & pgvector lesson?
Yes. Every Vector Databases: Pinecone, Weaviate & pgvector lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Weaviate Schema Definition
- Importing Data Objects
- Weaviate GraphQL Queries
- Vectorizer Modules and Auto-Embedding