Importowanie obiektów danych
Nauczy się Pan/Pani wydajnie importować obiekty danych do instancji Weaviate i nimi zarządzać, wraz z powiązanymi wektorami.
Importowanie obiektów danych to bezpłatna lekcja Vector Databases: Pinecone, Weaviate & pgvector na CoddyKit. To lekcja 2 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej Vector Databases: Pinecone, Weaviate & pgvector, a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs Vector Databases: Pinecone, Weaviate & pgvector zawiera 4 lekcji w sumie.
Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.
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!
Często zadawane pytania
Czy lekcja „Importowanie obiektów danych” jest bezpłatna?
Tak — pełny tekst „Importowanie obiektów danych” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu Vector Databases: Pinecone, Weaviate & pgvector, przejdź na CoddyKit PRO. Kurs Vector Databases: Pinecone, Weaviate & pgvector zawiera 4 lekcji w sumie.
Co nauczysz się w „Importowanie obiektów danych”?
Nauczy się Pan/Pani wydajnie importować obiekty danych do instancji Weaviate i nimi zarządzać, wraz z powiązanymi wektorami. Ćwiczysz Vector Databases: Pinecone, Weaviate & pgvector z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.
Czy potrzebuję doświadczenia, aby zacząć Vector Databases: Pinecone, Weaviate & pgvector?
Nie wymagamy żadnego doświadczenia. Vector Databases: Pinecone, Weaviate & pgvector w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 2 z 4.
Ile czasu zajmuje lekcja „Importowanie obiektów danych”?
Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.
Czy mogę pisać i uruchamiać kod w tej lekcji Vector Databases: Pinecone, Weaviate & pgvector?
Tak. Każda lekcja Vector Databases: Pinecone, Weaviate & pgvector zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.
Wszystkie lekcje w tym kursie
- Definiowanie schematu Weaviate
- Importowanie obiektów danych
- Zapytania GraphQL w Weaviate
- Moduły wektoryzacji i automatyczne embeddingi