0Pricing
Vector Databases: Pinecone, Weaviate & pgvector · Урок

Импорт объектов данных

Научитесь эффективно импортировать объекты данных в экземпляр Weaviate и управлять ими, включая связанные векторы.

«Импорт объектов данных» — бесплатный урок Vector Databases: Pinecone, Weaviate & pgvector на CoddyKit. Это урок 2 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения 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!

Часто задаваемые вопросы

Урок «Импорт объектов данных» бесплатный?

Да — полный текст урока «Импорт объектов данных» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Vector Databases: Pinecone, Weaviate & pgvector, подпишись на CoddyKit PRO. Курс Vector Databases: Pinecone, Weaviate & pgvector содержит 4 уроков всего.

Чему я научусь в уроке «Импорт объектов данных»?

Научитесь эффективно импортировать объекты данных в экземпляр Weaviate и управлять ими, включая связанные векторы. Ты практикуешь Vector Databases: Pinecone, Weaviate & pgvector с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Vector Databases: Pinecone, Weaviate & pgvector?

Предыдущий опыт не требуется. Vector Databases: Pinecone, Weaviate & pgvector на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 2 из 4.

Сколько времени занимает урок «Импорт объектов данных»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Vector Databases: Pinecone, Weaviate & pgvector?

Да. Каждый урок Vector Databases: Pinecone, Weaviate & pgvector включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Определение схемы Weaviate
  2. Импорт объектов данных
  3. Запросы GraphQL в Weaviate
  4. Модули векторизации и автоматическое создание эмбеддингов
← Назад к Vector Databases: Pinecone, Weaviate & pgvector