Skip to main content
Weaviate Docs (migrated from docs.weaviate.io) Docs

Search documentation

Type to search this documentation.

On this pageOverview

Quickstart: With Cloud resources

Weaviate is an open-source vector database built to power AI applications. This quickstart guide will show you how to:

  1. Set up a collection - Create a collection and import data into it.
  2. Search - Perform a similarity (vector) search on your data.
  3. RAG - Perform Retrieval Augmented Generation (RAG) with a generative model.
  4. Query Agent - Get answers from your data by using a natural language prompt/question. Cloud only

If you encounter any issues along the way or have additional questions, use the Ask AI feature.

A Weaviate Cloud free cluster - you will need an admin API key and a REST endpoint URL to connect to your instance. See the instructions below for more info. If you don't want to use Weaviate Cloud, check out the Local Quickstart with Docker.

How to set up a Weaviate Cloud free cluster

Go to the Weaviate Cloud console and create a free cluster as shown in the interactive example below.

How to retrieve Weaviate Cloud credentials (WEAVIATE_API_KEY and WEAVIATE_URL)

After you create a Weaviate Cloud instance, you will need the:

  • REST Endpoint URL and the
  • Administrator API Key.

You can retrieve them both from the WCD console as shown in the interactive example below.

Once you have the REST Endpoint URL and the admin API key, you can connect to your cluster, and work with Weaviate.


Follow the instructions below to install one of the official client libraries, available in Python, JavaScript/TypeScript, Go, and Java.

Python
pip install -U "weaviate-client[agents]"
JavaScript/TypeScript
npm install weaviate-client weaviate-agents
Go
go get github.com/weaviate/weaviate-go-client/v5
Java
<dependency>
  <groupId>io.weaviate</groupId>
  <artifactId>client6</artifactId>
  <version>6.2.0</version> <!-- Check latest version: https://github.com/weaviate/java-client  -->
</dependency>
C#
<PackageReference Include="Weaviate.Client" Version="1.0.0" />

There are two paths you can choose from when importing data:

The following example creates a collection called Movie. The data will be vectorized with the Weaviate EmbeddingsWeaviate Embeddings is a managed embedding inference service for Weaviate Cloud users (embedding model provider). It generates vector embeddings for your data and queries directly from a Weaviate Cloud database instance. model provider. You are also free to use any other available embedding model provider.

Python
import weaviate
from weaviate.classes.config import Configure
import os

# Best practice: store your credentials in environment variables
weaviate_url = os.environ["WEAVIATE_URL"]
weaviate_api_key = os.environ["WEAVIATE_API_KEY"]

# Step 1.1: Connect to your Weaviate Cloud instance
with weaviate.connect_to_weaviate_cloud(
    cluster_url=weaviate_url,
    auth_credentials=weaviate_api_key,
) as client:
TypeScript
import weaviate, { WeaviateClient, ApiKey, vectors } from 'weaviate-client';

// Best practice: store your credentials in environment variables
const weaviateUrl = process.env.WEAVIATE_URL!;
const weaviateApiKey = process.env.WEAVIATE_API_KEY!;

// Step 1.1: Connect to your Weaviate Cloud instance
const client: WeaviateClient = await weaviate.connectToWeaviateCloud(
  weaviateUrl,
  {
    authCredentials: new ApiKey(weaviateApiKey),
  }
);

The collection also contains a configuration for the generative (RAG) integration:

goraw
import (
  "context"
  "fmt"
  "os"

  "github.com/weaviate/weaviate-go-client/v5/weaviate"
  "github.com/weaviate/weaviate-go-client/v5/weaviate/auth"
  "github.com/weaviate/weaviate/entities/models"
)

func main() {
  // Best practice: store your credentials in environment variables
  weaviateURL := os.Getenv("WEAVIATE_HOST")
  weaviateAPIKey := os.Getenv("WEAVIATE_API_KEY")

  // Step 1.1: Connect to your Weaviate Cloud instance
  cfg := weaviate.Config{
    Host:       weaviateURL,
    Scheme:     "https",
    AuthConfig: auth.ApiKey{Value: weaviateAPIKey},
  }
  client, err := weaviate.NewClient(cfg)
  if err != nil {
    panic(err)
  }
javaraw
import io.weaviate.client6.v1.api.WeaviateClient;
import io.weaviate.client6.v1.api.collections.CollectionHandle;
import io.weaviate.client6.v1.api.collections.Property;
import io.weaviate.client6.v1.api.collections.VectorConfig;
import io.weaviate.client6.v1.api.collections.WeaviateObject;
import io.weaviate.client6.v1.api.collections.batch.BatchContext;

import java.util.List;
import java.util.Map;

public class QuickstartCreate {

  public static void main(String[] args) throws Exception {
    WeaviateClient client = null;
    String collectionName = "Movie";

    try {
      // Best practice: store your credentials in environment variables
      String weaviateUrl = System.getenv("WEAVIATE_URL");
      String weaviateApiKey = System.getenv("WEAVIATE_API_KEY");

      // Step 1.1: Connect to your Weaviate Cloud instance
      client =
          WeaviateClient.connectToWeaviateCloud(weaviateUrl, weaviateApiKey);
C#
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Weaviate.Client;
using Weaviate.Client.Models;

namespace WeaviateProject.Examples
{
    public class QuickstartCreate
    {
        public static async Task Run()
        {
            // Best practice: store your credentials in environment variables
            string weaviateUrl = Environment.GetEnvironmentVariable("WEAVIATE_URL");
            string weaviateApiKey = Environment.GetEnvironmentVariable("WEAVIATE_API_KEY");
            string collectionName = "Movie";

            // Connect to your Weaviate Cloud instance
            var client = await Connect.Cloud(weaviateUrl, weaviateApiKey);

The following example creates a collection called Movie. The data should already contain the pre-computed vector embeddingsVector embeddings generated by an embedding model (from a provider like OpenAI, Anthropic, etc.).. This option is useful for when you are migrating data from a different vector database.

Python
import weaviate
from weaviate.classes.config import Configure
from weaviate.classes.data import DataObject
import os

# Best practice: store your credentials in environment variables
weaviate_url = os.environ["WEAVIATE_URL"]
weaviate_api_key = os.environ["WEAVIATE_API_KEY"]

# Step 1.1: Connect to your Weaviate Cloud instance
with weaviate.connect_to_weaviate_cloud(
    cluster_url=weaviate_url,
    auth_credentials=weaviate_api_key,
) as client:
TypeScript
import weaviate, { WeaviateClient, ApiKey, vectors } from 'weaviate-client';

// Best practice: store your credentials in environment variables
const weaviateUrl = process.env.WEAVIATE_URL!;
const weaviateApiKey = process.env.WEAVIATE_API_KEY!;

// Step 1.1: Connect to your Weaviate Cloud instance
const client: WeaviateClient = await weaviate.connectToWeaviateCloud(
  weaviateUrl,
  {
    authCredentials: new ApiKey(weaviateApiKey),
  }
);

The collection also contains a configuration for the generative (RAG) integration:

goraw
import (
  "context"
  "fmt"
  "os"

  "github.com/weaviate/weaviate-go-client/v5/weaviate"
  "github.com/weaviate/weaviate-go-client/v5/weaviate/auth"
  "github.com/weaviate/weaviate/entities/models"
)

func main() {
  // Best practice: store your credentials in environment variables
  weaviateURL := os.Getenv("WEAVIATE_HOST")
  weaviateAPIKey := os.Getenv("WEAVIATE_API_KEY")

  // Step 1.1: Connect to your Weaviate Cloud instance
  cfg := weaviate.Config{
    Host:       weaviateURL,
    Scheme:     "https",
    AuthConfig: auth.ApiKey{Value: weaviateAPIKey},
  }
  client, err := weaviate.NewClient(cfg)
  if err != nil {
    panic(err)
  }
javaraw
import io.weaviate.client6.v1.api.WeaviateClient;
import io.weaviate.client6.v1.api.collections.CollectionHandle;
import io.weaviate.client6.v1.api.collections.Property;
import io.weaviate.client6.v1.api.collections.VectorConfig;
import io.weaviate.client6.v1.api.collections.Vectors;
import io.weaviate.client6.v1.api.collections.WeaviateObject;
import io.weaviate.client6.v1.api.collections.batch.BatchContext;
import java.util.List;
import java.util.Map;

public class QuickstartCreateVectors {

  public static void main(String[] args) throws Exception {
    WeaviateClient client = null;
    String collectionName = "Movie";

    try {
      // Best practice: store your credentials in environment variables
      String weaviateUrl = System.getenv("WEAVIATE_URL");
      String weaviateApiKey = System.getenv("WEAVIATE_API_KEY");

      // Step 1.1: Connect to your Weaviate Cloud instance
      client =
          WeaviateClient.connectToWeaviateCloud(weaviateUrl, weaviateApiKey);
C#
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Weaviate.Client;
using Weaviate.Client.Models;

namespace WeaviateProject.Examples
{
    public class QuickstartCreateVectors
    {
        public static async Task Run()
        {
            string weaviateUrl = Environment.GetEnvironmentVariable("WEAVIATE_URL");
            string weaviateApiKey = Environment.GetEnvironmentVariable("WEAVIATE_API_KEY");
            string collectionName = "Movie";

            var client = await Connect.Cloud(weaviateUrl, weaviateApiKey);

Semantic search finds results based on meaning. This is called nearText in Weaviate. The following example searches for 2 objects (limit) whose meaning is most similar to that of sci-fi.

Python
import weaviate
import os, json

# Best practice: store your credentials in environment variables
weaviate_url = os.environ["WEAVIATE_URL"]
weaviate_api_key = os.environ["WEAVIATE_API_KEY"]

# Step 2.1: Connect to your Weaviate Cloud instance
with weaviate.connect_to_weaviate_cloud(
    cluster_url=weaviate_url,
    auth_credentials=weaviate_api_key,
) as client:

    # Step 2.2: Use this collection
    movies = client.collections.use("Movie")

    # Step 2.3: Perform a semantic search with NearText
    # highlight-start
JavaScript/TypeScript
import weaviate, { WeaviateClient, ApiKey } from 'weaviate-client';

// Best practice: store your credentials in environment variables
const weaviateUrl = process.env.WEAVIATE_URL!;
const weaviateApiKey = process.env.WEAVIATE_API_KEY!;

// Step 2.1: Connect to your Weaviate Cloud instance
const client: WeaviateClient = await weaviate.connectToWeaviateCloud(
  weaviateUrl,
  {
    authCredentials: new ApiKey(weaviateApiKey),
  }
);

// Step 2.2: Use this collection
const movies = client.collections.get('Movie');

// Step 2.3: Perform a semantic search with NearText
// highlight-start
Go
import (
  "context"
  "encoding/json"
  "fmt"
  "os"

  "github.com/weaviate/weaviate-go-client/v5/weaviate"
  "github.com/weaviate/weaviate-go-client/v5/weaviate/auth"
  "github.com/weaviate/weaviate-go-client/v5/weaviate/graphql"
)

func main() {
  // Best practice: store your credentials in environment variables
  weaviateURL := os.Getenv("WEAVIATE_HOST")
  weaviateAPIKey := os.Getenv("WEAVIATE_API_KEY")

  // Step 1.1: Connect to your Weaviate Cloud instance
  cfg := weaviate.Config{
    Host:       weaviateURL,
    Scheme:     "https",
    AuthConfig: auth.ApiKey{Value: weaviateAPIKey},
  }
  client, err := weaviate.NewClient(cfg)
  if err != nil {
    panic(err)
  }

  // Step 2.2: Perform a semantic search with NearText
  // highlight-start
Java
import io.weaviate.client6.v1.api.WeaviateClient;import io.weaviate.client6.v1.api.collections.CollectionHandle;import com.fasterxml.jackson.databind.ObjectMapper; // For pretty-printing JSONimport java.util.Map;public class QuickstartQueryNearText {  public static void main(String[] args) throws Exception {    WeaviateClient client = null;    try {      // Best practice: store your credentials in environment variables      String weaviateUrl = System.getenv("WEAVIATE_URL");      String weaviateApiKey = System.getenv("WEAVIATE_API_KEY");      // Step 2.1: Connect to your Weaviate Cloud instance      client =          WeaviateClient.connectToWeaviateCloud(weaviateUrl, weaviateApiKey);      // Step 2.2: Perform a semantic search with NearText      CollectionHandle<Map<String, Object>> movies =          client.collections.use("Movie");      ObjectMapper objectMapper = new ObjectMapper();      var response = movies.query.nearText("sci-fi",          q -> q.limit(2).returnProperties("title", "description", "genre"));      // Inspect the results      System.out.println("--- Query Results ---");      for (var obj : response.objects()) {        System.out.println(objectMapper.writerWithDefaultPrettyPrinter()            .writeValueAsString(obj.properties()));      }    } finally {      if (client != null) {        client.close(); // Free up resources      }    }  }}
C#
using System;using System.Text.Json;using System.Threading.Tasks;using Weaviate.Client;using Weaviate.Client.Models;namespace WeaviateProject.Examples{    public class QuickstartQueryNearText    {        public static async Task Run()        {            // Best practice: store your credentials in environment variables            string weaviateUrl = Environment.GetEnvironmentVariable("WEAVIATE_URL");            string weaviateApiKey = Environment.GetEnvironmentVariable("WEAVIATE_API_KEY");            // Step 2.1: Connect to your Weaviate Cloud instance            var client = await Connect.Cloud(weaviateUrl, weaviateApiKey);            // Step 2.2: Perform a semantic search with NearText            var movies = client.Collections.Use("Movie");            var response = await movies.Query.NearText(                "sci-fi",                limit: 2,                returnProperties: ["title", "description", "genre"]            );            // Inspect the results            Console.WriteLine("--- Query Results ---");            foreach (var obj in response.Objects)            {                Console.WriteLine(                    JsonSerializer.Serialize(                        obj.Properties,                        new JsonSerializerOptions { WriteIndented = true }                    )                );            }        }    }}

Semantic search finds results based on meaning. This is called nearVector in Weaviate. The following example searches for 2 objects (limit) whose vector is most similar to the query vector.

Python
import weaviate
import os, json

# Best practice: store your credentials in environment variables
weaviate_url = os.environ["WEAVIATE_URL"]
weaviate_api_key = os.environ["WEAVIATE_API_KEY"]

# Step 2.1: Connect to your Weaviate Cloud instance
with weaviate.connect_to_weaviate_cloud(
    cluster_url=weaviate_url,
    auth_credentials=weaviate_api_key,
) as client:

    # Step 2.2: Use this collection
    movies = client.collections.use("Movie")

    # Step 2.3: Perform a vector search with NearVector
    # highlight-start
JavaScript/TypeScript
import weaviate, { WeaviateClient, ApiKey } from 'weaviate-client';

// Best practice: store your credentials in environment variables
const weaviateUrl = process.env.WEAVIATE_URL!;
const weaviateApiKey = process.env.WEAVIATE_API_KEY!;

// Step 2.1: Connect to your Weaviate Cloud instance
const client: WeaviateClient = await weaviate.connectToWeaviateCloud(
  weaviateUrl,
  {
    authCredentials: new ApiKey(weaviateApiKey),
  }
);

// Step 2.2: Use this collection
const movies = client.collections.get('Movie');

// Step 2.3: Perform a vector search with NearVector
// highlight-start
Go
Java
import io.weaviate.client6.v1.api.WeaviateClient;import io.weaviate.client6.v1.api.collections.CollectionHandle;import com.fasterxml.jackson.databind.ObjectMapper; // For pretty-printing JSONimport java.util.Map;public class QuickstartQueryNearVector {  public static void main(String[] args) throws Exception {    WeaviateClient client = null;    try {      // Best practice: store your credentials in environment variables      String weaviateUrl = System.getenv("WEAVIATE_URL");      String weaviateApiKey = System.getenv("WEAVIATE_API_KEY");      // Step 2.1: Connect to your Weaviate Cloud instance      client =          WeaviateClient.connectToWeaviateCloud(weaviateUrl, weaviateApiKey);      // Step 2.2: Perform a vector search with NearVector      CollectionHandle<Map<String, Object>> movies =          client.collections.use("Movie");      ObjectMapper objectMapper = new ObjectMapper();      // Use primitive float[] for v6      float[] queryVector =          new float[] {0.11f, 0.21f, 0.31f, 0.41f, 0.51f, 0.61f, 0.71f, 0.81f};      var response = movies.query.nearVector(queryVector,          q -> q.limit(2).returnProperties("title", "description", "genre"));      // Inspect the results      System.out.println("--- Query Results ---");      for (var obj : response.objects()) {        System.out.println(objectMapper.writerWithDefaultPrettyPrinter()            .writeValueAsString(obj.properties()));      }    } finally {      if (client != null) {        client.close(); // Free up resources      }    }  }}
C#
using System;using System.Text.Json;using System.Threading.Tasks;using Weaviate.Client;namespace WeaviateProject.Examples{    public class QuickstartQueryNearVector    {        public static async Task Run()        {            // Best practice: store your credentials in environment variables            string weaviateUrl = Environment.GetEnvironmentVariable("WEAVIATE_URL");            string weaviateApiKey = Environment.GetEnvironmentVariable("WEAVIATE_API_KEY");            // Step 2.1: Connect to your Weaviate Cloud instance            var client = await Connect.Cloud(weaviateUrl, weaviateApiKey);            // Step 2.2: Perform a vector search with NearVector            var movies = client.Collections.Use("Movie");            float[] queryVector = [0.11f, 0.21f, 0.31f, 0.41f, 0.51f, 0.61f, 0.71f, 0.81f];            var response = await movies.Query.NearVector(                queryVector,                limit: 2,                returnProperties: ["title", "description", "genre"]            );            // Inspect the results            Console.WriteLine("--- Query Results ---");            foreach (var obj in response.Objects)            {                Console.WriteLine(                    JsonSerializer.Serialize(                        obj.Properties,                        new JsonSerializerOptions { WriteIndented = true }                    )                );            }        }    }}
Example response
JSON
{
  "genre": "Science Fiction",
  "title": "The Matrix",
  "description": "A computer hacker learns about the true nature of reality and his role in the war against its controllers."
}
{
  "genre": "Fantasy",
  "title": "The Lord of the Rings: The Fellowship of the Ring",
  "description": "A meek Hobbit and his companions set out on a perilous journey to destroy a powerful ring and save Middle-earth."
}

Step 3: Retrieval augmented generation (RAG)

Section titled “Step 3: Retrieval augmented generation (RAG)”

Retrieval augmented generation (RAG), also called generative search, works by prompting a large language model (LLM) with a combination of a user query and data retrieved from a database.

The following example combines the semantic search for the query sci-fi with a prompt to generate a tweet using the Anthropic generative model (generative-anthropic).

Python
import osimport weaviatefrom weaviate.classes.generate import GenerativeConfig# Best practice: store your credentials in environment variablesweaviate_url = os.environ["WEAVIATE_URL"]weaviate_api_key = os.environ["WEAVIATE_API_KEY"]anthropic_api_key = os.environ["ANTHROPIC_API_KEY"]# Step 2.1: Connect to your Weaviate Cloud instancewith weaviate.connect_to_weaviate_cloud(    cluster_url=weaviate_url,    auth_credentials=weaviate_api_key,    headers={"X-Anthropic-Api-Key": anthropic_api_key},) as client:    # Step 2.2: Use this collection    movies = client.collections.use("Movie")    # Step 2.3: Perform RAG with on NearText results    response = movies.generate.near_text(        query="sci-fi",        limit=1,        grouped_task="Write a tweet with emojis about this movie.",        generative_provider=GenerativeConfig.anthropic(            model="claude-haiku-4-5"        ),  # Configure the Anthropic generative integration for RAG    )    print(response.generative.text)  # Inspect the results
JavaScript/TypeScript
import weaviate, { WeaviateClient, ApiKey, generativeParameters } from 'weaviate-client';// Best practice: store your credentials in environment variablesconst weaviateUrl = process.env.WEAVIATE_URL!;const weaviateApiKey = process.env.WEAVIATE_API_KEY!;const anthropicApiKey = process.env.ANTHROPIC_API_KEY!;// Step 2.1: Connect to your Weaviate Cloud instanceconst client: WeaviateClient = await weaviate.connectToWeaviateCloud(  weaviateUrl,  {    authCredentials: new ApiKey(weaviateApiKey),    headers: { 'X-Anthropic-Api-Key': anthropicApiKey },  });// Step 2.2: Use this collectionconst movies = client.collections.get('Movie');// Step 2.3: Perform RAG with on NearText resultsconst response = await movies.generate.nearText(  'sci-fi',  {    groupedTask: 'Write a tweet with emojis about this movie.',    config: generativeParameters.anthropic({      model: "claude-haiku-4-5",    }),  },  {    limit: 1,  });console.log(response.generative); // Inspect the resultsawait client.close(); // Free up resources
Go
import (  "context"  "fmt"  "os"  "github.com/weaviate/weaviate-go-client/v5/weaviate"  "github.com/weaviate/weaviate-go-client/v5/weaviate/auth"  "github.com/weaviate/weaviate-go-client/v5/weaviate/graphql")func main() {  // Best practice: store your credentials in environment variables  weaviateURL := os.Getenv("WEAVIATE_URL")  weaviateAPIKey := os.Getenv("WEAVIATE_API_KEY")  anthropicAPIKey := os.Getenv("ANTHROPIC_API_KEY")  // Step 2.1: Connect to your Weaviate Cloud instance  headers := map[string]string{    "X-Anthropic-Api-Key": anthropicAPIKey,  }  cfg := weaviate.Config{    Host:       weaviateURL,    Scheme:     "https",    AuthConfig: auth.ApiKey{Value: weaviateAPIKey},    Headers:    headers,  }  client, err := weaviate.NewClient(cfg)  if err != nil {    panic(err)  }  // Step 2.2: Perform RAG with NearText results  title := graphql.Field{Name: "title"}  description := graphql.Field{Name: "description"}  genre := graphql.Field{Name: "genre"}  nearText := client.GraphQL().NearTextArgBuilder().    WithConcepts([]string{"sci-fi"})  generate := graphql.NewGenerativeSearch().GroupedResult("Write a tweet with emojis about this movie.")  result, err := client.GraphQL().Get().    WithClassName("Movie").    WithNearText(nearText).    WithLimit(1).    WithFields(title, description, genre).    WithGenerativeSearch(generate).    Do(context.Background())  if err != nil {    panic(err)  }  // Inspect the results  if result.Errors != nil {    fmt.Printf("Error: %v\n", result.Errors)    return  }  fmt.Printf("%v", result)
Java
import io.weaviate.client6.v1.api.WeaviateClient;import io.weaviate.client6.v1.api.collections.CollectionHandle;import io.weaviate.client6.v1.api.collections.generate.GenerativeProvider;import java.util.Map;public class QuickstartQueryNearTextRAG {  public static void main(String[] args) throws Exception {    WeaviateClient client = null;    try {      // Best practice: store your credentials in environment variables      String weaviateUrl = System.getenv("WEAVIATE_URL");      String weaviateApiKey = System.getenv("WEAVIATE_API_KEY");      String anthropicApiKey = System.getenv("ANTHROPIC_API_KEY");      // Step 2.1: Connect to your Weaviate Cloud instance      client = WeaviateClient.connectToWeaviateCloud(weaviateUrl,          weaviateApiKey, config -> config              .setHeaders(Map.of("X-Anthropic-Api-Key", anthropicApiKey)));      // Step 2.2: Perform RAG with nearText results      CollectionHandle<Map<String, Object>> movies =          client.collections.use("Movie");      var response = movies.generate.nearText("sci-fi",          // Query configuration (nearText and limit)          q -> q.limit(1).returnProperties("title", "description", "genre"),          // Generative configuration (RAG task)          g -> g.groupedTask("Write a tweet with emojis about this movie.",              c -> c.generativeProvider(GenerativeProvider                  .anthropic(o -> o.model("claude-haiku-4-5"))))); // The model to use      // Inspect the results      // Use .generative() to access the generative result      System.out.println(response.generative().text());    } finally {      if (client != null) {        client.close(); // Free up resources      }    }  }}
C#
using System;using System.Collections.Generic;using System.Text.Json;using System.Threading.Tasks;using Weaviate.Client;using Weaviate.Client.Models;using Weaviate.Client.Models.Generative;namespace WeaviateProject.Examples{    public class QuickstartQueryNearTextRAG    {        public static async Task Run()        {            // Best practice: store your credentials in environment variables            string weaviateUrl = Environment.GetEnvironmentVariable("WEAVIATE_URL");            string weaviateApiKey = Environment.GetEnvironmentVariable("WEAVIATE_API_KEY");            string anthropicApiKey = Environment.GetEnvironmentVariable("ANTHROPIC_API_KEY");            // Step 3.1: Connect to your Weaviate Cloud instance            var client = await Connect.Cloud(                weaviateUrl,                weaviateApiKey,                headers: new Dictionary<string, string>                {                    { "X-Anthropic-Api-Key", anthropicApiKey },                }            );            // Step 3.2: Perform RAG with nearText results            var movies = client.Collections.Use("Movie");            var response = await movies.Generate.NearText(                "sci-fi",                limit: 1,                returnProperties: ["title", "description", "genre"],                groupedTask: new GroupedTask("Write a tweet with emojis about this movie."),                provider: new Providers.Anthropic                {                    Model = "claude-haiku-4-5", // The model to use                }            );            // Inspect the results            Console.WriteLine(JsonSerializer.Serialize(response.Generative.Values));        }    }}

Retrieval augmented generation (RAG), also called generative search, works by prompting a large language model (LLM) with a combination of a user query and data retrieved from a database.

The following example combines the vector similarity search with a prompt to generate a tweet using the Anthropic generative model (generative-anthropic).

Python
import osimport weaviatefrom weaviate.classes.generate import GenerativeConfig# Best practice: store your credentials in environment variablesweaviate_url = os.environ["WEAVIATE_URL"]weaviate_api_key = os.environ["WEAVIATE_API_KEY"]anthropic_api_key = os.environ["ANTHROPIC_API_KEY"]# Step 2.1: Connect to your Weaviate Cloud instancewith weaviate.connect_to_weaviate_cloud(    cluster_url=weaviate_url,    auth_credentials=weaviate_api_key,    headers={"X-Anthropic-Api-Key": anthropic_api_key},) as client:    # Step 2.2: Use this collection    movies = client.collections.use("Movie")    # Step 2.3: Perform RAG with on NearVector results    response = movies.generate.near_vector(        near_vector=[0.11, 0.21, 0.31, 0.41, 0.51, 0.61, 0.71, 0.81],        limit=1,        grouped_task="Write a tweet with emojis about this movie.",        generative_provider=GenerativeConfig.anthropic(            model="claude-haiku-4-5"        ),  # Configure the Anthropic generative integration for RAG    )    print(response.generative.text)  # Inspect the results
JavaScript/TypeScript
import weaviate, { WeaviateClient, ApiKey, generativeParameters } from 'weaviate-client';// Best practice: store your credentials in environment variablesconst weaviateUrl = process.env.WEAVIATE_URL!;const weaviateApiKey = process.env.WEAVIATE_API_KEY!;const anthropicApiKey = process.env.ANTHROPIC_API_KEY!;// Step 2.1: Connect to your Weaviate Cloud instanceconst client: WeaviateClient = await weaviate.connectToWeaviateCloud(  weaviateUrl,  {    authCredentials: new ApiKey(weaviateApiKey),    headers: { 'X-Anthropic-Api-Key': anthropicApiKey },  });// Step 2.2: Use this collectionconst movies = client.collections.get('Movie');// Step 2.3: Perform RAG with on NearVector resultsconst response = await movies.generate.nearVector(  [0.11, 0.21, 0.31, 0.41, 0.51, 0.61, 0.71, 0.81],  {    groupedTask: 'Write a tweet with emojis about this movie.',    config: generativeParameters.anthropic({      model: "claude-haiku-4-5",    }),  },  {    limit: 1,  });console.log(response.generative); // Inspect the resultsawait client.close(); // Free up resources
Go
Java
import io.weaviate.client6.v1.api.WeaviateClient;import io.weaviate.client6.v1.api.collections.CollectionHandle;import io.weaviate.client6.v1.api.collections.generate.GenerativeProvider;import java.util.Map;public class QuickstartQueryNearVectorRAG {  public static void main(String[] args) throws Exception {    WeaviateClient client = null;    try {      // Best practice: store your credentials in environment variables      String weaviateUrl = System.getenv("WEAVIATE_URL");      String weaviateApiKey = System.getenv("WEAVIATE_API_KEY");      String anthropicApiKey = System.getenv("ANTHROPIC_API_KEY");      // Step 2.1: Connect to your Weaviate Cloud instance      client = WeaviateClient.connectToWeaviateCloud(weaviateUrl,          weaviateApiKey, config -> config              .setHeaders(Map.of("X-Anthropic-Api-Key", anthropicApiKey)));      // Step 2.2: Perform RAG with NearVector results      CollectionHandle<Map<String, Object>> movies =          client.collections.use("Movie");      // Use primitive float[] for v6      float[] queryVector =          new float[] {0.11f, 0.21f, 0.31f, 0.41f, 0.51f, 0.61f, 0.71f, 0.81f};      var response = movies.generate.nearVector(queryVector,          q -> q.limit(1).returnProperties("title", "description", "genre"),          // Generative configuration (RAG task)          g -> g.groupedTask("Write a tweet with emojis about this movie.",              c -> c.generativeProvider(GenerativeProvider                  .anthropic(o -> o.model("claude-haiku-4-5"))))); // The model to use      // Inspect the results      // Use .generative() to access the generative result      System.out.println(response.generative().text());    } finally {      if (client != null) {        client.close(); // Free up resources      }    }  }}
C#
using System;using System.Collections.Generic;using System.Text.Json;using System.Threading.Tasks;using Weaviate.Client;using Weaviate.Client.Models;using Weaviate.Client.Models.Generative;namespace WeaviateProject.Examples{    public class QuickstartQueryNearVectorRAG    {        public static async Task Run()        {            // Best practice: store your credentials in environment variables            string weaviateUrl = Environment.GetEnvironmentVariable("WEAVIATE_URL");            string weaviateApiKey = Environment.GetEnvironmentVariable("WEAVIATE_API_KEY");            string anthropicApiKey = Environment.GetEnvironmentVariable("ANTHROPIC_API_KEY");            // Step 3.1: Connect to your Weaviate Cloud instance            var client = await Connect.Cloud(                weaviateUrl,                weaviateApiKey,                headers: new Dictionary<string, string>                {                    { "X-Anthropic-Api-Key", anthropicApiKey },                }            );            // Step 3.2: Perform RAG with NearVector results            var movies = client.Collections.Use("Movie");            float[] queryVector = [0.11f, 0.21f, 0.31f, 0.41f, 0.51f, 0.61f, 0.71f, 0.81f];            var response = await movies.Generate.NearVector(                vectors: queryVector,                limit: 1,                returnProperties: ["title", "description", "genre"],                groupedTask: new GroupedTask("Write a tweet with emojis about this movie."),                provider: new Providers.Anthropic                {                    Model = "claude-haiku-4-5", // The model to use                }            );            // Inspect the results            Console.WriteLine(JsonSerializer.Serialize(response.Generative.Values));        }    }}
Example response
JSON
🕶️ Unplug from the system & join Neo's journey 💊🐰

"The Matrix" will blow your mind 🤯 as reality unravels 🌀

Kung-fu, slow-mo & mind-bending sci-fi 🥋🕴️

Are you ready to see how deep the rabbit hole goes? 🔴🔵 #TheMatrix #WakeUp

Weaviate Cloud only

The Weaviate Query Agent is a pre-built agentic service designed to answer natural language queries based on the data stored in Weaviate Cloud. The user simply provides a prompt/question in natural language, and the Query Agent takes care of all intervening steps to provide an answer.

Python
import osimport weaviatefrom weaviate.agents.query import QueryAgent# Best practice: store your credentials in environment variablesweaviate_url = os.environ["WEAVIATE_URL"]weaviate_api_key = os.environ["WEAVIATE_API_KEY"]# Step 2.1: Connect to your Weaviate Cloud instancewith weaviate.connect_to_weaviate_cloud(    cluster_url=weaviate_url,    auth_credentials=weaviate_api_key,) as client:    # Step 2.2: Instantiate a new agent object    qa = QueryAgent(client=client, collections=["Movie"])    # Step 2.3: Perform a query using Search Mode    response = qa.search("Find a cool sci-fi movie.", limit=1)    # Print the response    for obj in response.search_results.objects:        print(f"Movie: {obj.properties['title']} - {obj.properties['description']}")
JavaScript/TypeScript
import weaviate, { WeaviateClient, ApiKey } from 'weaviate-client';
import { QueryAgent } from 'weaviate-agents';

// Best practice: store your credentials in environment variables
const weaviateUrl = process.env.WEAVIATE_URL!;
const weaviateApiKey = process.env.WEAVIATE_API_KEY!;

// Step 2.1: Connect to your Weaviate Cloud instance
const client: WeaviateClient = await weaviate.connectToWeaviateCloud(
  weaviateUrl,
  {
    authCredentials: new ApiKey(weaviateApiKey),
  }
);

// Step 2.2: Use this collection
// Instantiate a new agent object
const queryAgent = new QueryAgent(
  client, {
  collections: ['Movie'],

});

// Perform a search using Search Mode (retrieval only, no answer generation)
const basicSearchResponse = await queryAgent.search("Find a cool sci-fi movie.", {
  limit: 1
})

// Access the search results
for (const obj of basicSearchResponse.searchResults.objects) {
  console.log(`Movie: ${obj.properties['title']} - ${obj.properties['description']}`)
}

await client.close(); // Free up resources

Here is the printed response:

JSON
Movie: The Matrix - A computer hacker learns about the true nature of reality and his role in the war against its controllers.

We recommend you check out the following resources to continue learning about Weaviate.

Have a question or feedback? Here's how to reach us.

Suggest an edit

Propose a replacement for this page. The site team reviews it before applying any changes.

Export
Documentation menu