导入数据对象
学习将数据对象及其关联向量高效导入并管理到 Weaviate 实例中。
导入数据对象 是 CoddyKit 上的免费 Vector Databases: Pinecone, Weaviate & pgvector 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Vector Databases: Pinecone, Weaviate & pgvector 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Vector Databases: Pinecone, Weaviate & pgvector 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
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!
常见问题解答
「导入数据对象」课时是免费的吗?
是的 — 「导入数据对象」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Vector Databases: Pinecone, Weaviate & pgvector 课程的其余内容,请升级到 CoddyKit PRO。 Vector Databases: Pinecone, Weaviate & pgvector 课程共包含 4 节课。
「导入数据对象」这节课中我会学到什么?
学习将数据对象及其关联向量高效导入并管理到 Weaviate 实例中。 你通过在浏览器中直接运行的动手代码来练习 Vector Databases: Pinecone, Weaviate & pgvector,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Vector Databases: Pinecone, Weaviate & pgvector 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Vector Databases: Pinecone, Weaviate & pgvector 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。
「导入数据对象」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Vector Databases: Pinecone, Weaviate & pgvector 课中编写并运行代码吗?
能。每节 Vector Databases: Pinecone, Weaviate & pgvector 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。