0Pricing
Vector Databases: Pinecone, Weaviate & pgvector · Lezione

Importare oggetti dati

Impari a importare e gestire in modo efficiente gli oggetti dati nella sua istanza Weaviate, inclusi i relativi vettori.

Importare oggetti dati è una lezione Vector Databases: Pinecone, Weaviate & pgvector gratuita su CoddyKit. Questa è la lezione 2 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Vector Databases: Pinecone, Weaviate & pgvector, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Vector Databases: Pinecone, Weaviate & pgvector include 4 lezioni in totale.

Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.

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!

Domande Frequenti

La lezione «Importare oggetti dati» è gratuita?

Sì — il testo completo di «Importare oggetti dati» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Vector Databases: Pinecone, Weaviate & pgvector, passa a CoddyKit PRO. Il corso Vector Databases: Pinecone, Weaviate & pgvector include 4 lezioni in totale.

Cosa imparerò in «Importare oggetti dati»?

Impari a importare e gestire in modo efficiente gli oggetti dati nella sua istanza Weaviate, inclusi i relativi vettori. Eserciti Vector Databases: Pinecone, Weaviate & pgvector con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare Vector Databases: Pinecone, Weaviate & pgvector?

Non è richiesta alcuna esperienza precedente. Vector Databases: Pinecone, Weaviate & pgvector su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 2 di 4.

Quanto tempo richiede la lezione «Importare oggetti dati»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione Vector Databases: Pinecone, Weaviate & pgvector?

Sì. Ogni lezione Vector Databases: Pinecone, Weaviate & pgvector include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. Definire lo schema di Weaviate
  2. Importare oggetti dati
  3. Query GraphQL in Weaviate
  4. Moduli vectorizer e auto-embedding
← Torna a Vector Databases: Pinecone, Weaviate & pgvector