Skip to main content
Go to documentation:
⌘U
Weaviate Database

Develop AI applications using Weaviate's APIs and tools

Deploy

Deploy, configure, and maintain Weaviate Database

Query Agent

Run agentic search over your Weaviate Cloud collections

Weaviate Cloud

Manage and scale Weaviate in the cloud

Engram

Persistent memory for LLM agents and applications

Additional resources

Integrations
Weaviate Academy

Need help?

Weaviate LogoAsk AI Assistant⌘K
Support
Community Forum
Contributor guide

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 feature.

Get started faster with AI

Build a working movie search app with natural language queries, vector search, and RAG in 5 steps.

Prerequisites​

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.


note
  • Cluster provisioning typically takes 1-3 minutes.
  • When the cluster is ready, Weaviate Cloud displays a checkmark (✔️) next to the cluster name.
  • Note that Weaviate Cloud may add a random suffix to cluster names to ensure uniqueness.
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.


REST vs gRPC endpoints

Weaviate supports both REST and gRPC protocols. For Weaviate Cloud deployments, you only need to provide the REST endpoint URL - the client will automatically configure gRPC.

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


Install a client library​

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

py docs  API docs
More infoCode snippets in the documentation reflect the latest client library and Weaviate Database version. Check the Release notes for specific versions.

If a snippet doesn't work or you have feedback, please open a GitHub issue.
pip install -U "weaviate-client[agents]"
npm install @weaviate/node @weaviate/agents
go get github.com/weaviate/weaviate-go-client/v5
go get github.com/weaviate/weaviate-go-client/v6
<dependency>
<groupId>io.weaviate</groupId>
<artifactId>client6</artifactId>
<version>6.3.1</version> <!-- Check latest version: https://github.com/weaviate/java-client -->
</dependency>
<PackageReference Include="Weaviate.Client" Version="1.0.0" />
Verify your setup

Before you create anything, you can also check that the client can reach your cluster:

py docs  API docs
More infoCode snippets in the documentation reflect the latest client library and Weaviate Database version. Check the Release notes for specific versions.

If a snippet doesn't work or you have feedback, please open a GitHub issue.
quickstart_check_readiness.py
import weaviate
from weaviate.classes.init import Auth
import os

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

client = weaviate.connect_to_weaviate_cloud(
cluster_url=weaviate_url,
auth_credentials=Auth.api_key(weaviate_api_key),
)

print(client.is_ready()) # Should print: `True`

client.close() # Free up resources
quickstart_check_readiness.ts
import weaviate, { WeaviateClient } from '@weaviate/node';

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

const client: WeaviateClient = await weaviate.connectToWeaviateCloud(
weaviateUrl, // Replace with your Weaviate Cloud URL
{
authCredentials: new weaviate.ApiKey(weaviateApiKey), // Replace with your Weaviate Cloud API key
}
);

var clientReadiness = await client.isReady();
console.log(clientReadiness); // Should return `true`

client.close(); // Close the client connection
quickstart/1_check_readiness/main.go
// Set these environment variables
// WEAVIATE_HOSTNAME your Weaviate instance hostname
// WEAVIATE_API_KEY your Weaviate instance API key

package main

import (
"context"
"fmt"
"os"

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

func main() {
cfg := weaviate.Config{
Host: os.Getenv("WEAVIATE_HOSTNAME"),
Scheme: "https",
AuthConfig: auth.ApiKey{Value: os.Getenv("WEAVIATE_API_KEY")},
}

client, err := weaviate.NewClient(cfg)
if err != nil {
fmt.Println(err)
}

// Check the connection
ready, err := client.Misc().ReadyChecker().Do(context.Background())
if err != nil {
panic(err)
}
fmt.Printf("%v", ready)
}
caution

This client uses the hostname parameter (without the https scheme) instead of a complete URL.

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

WeaviateClient client = WeaviateClient.connectToWeaviateCloud(
weaviateUrl, // Replace with your Weaviate Cloud URL
weaviateApiKey // Replace with your Weaviate Cloud key
);
System.out.println(client.isReady()); // Should print: `True`

client.close(); // Free up resources
// Best practice: store your credentials in environment variables
string weaviateUrl = Environment.GetEnvironmentVariable("WEAVIATE_URL");
string weaviateApiKey = Environment.GetEnvironmentVariable("WEAVIATE_API_KEY");

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

// GetMeta returns server info. A successful call indicates readiness.
var meta = await client.IsReady();
Console.WriteLine(meta);
caution

This client uses the hostname parameter (without the https scheme) instead of a complete URL.

# Best practice: store your credentials in environment variables
# export WEAVIATE_URL="YOUR_INSTANCE_URL" # Your Weaviate instance URL
# export WEAVIATE_API_KEY="YOUR_API_KEY" # Your Weaviate instance API key

curl -w "\nResponse code: %{http_code}\n" \
-H "Authorization: Bearer $WEAVIATE_API_KEY" \
$WEAVIATE_URL/v1/.well-known/ready

# You should see "Response code: 200" if the instance is ready

Some common first errors include:

What you seeWhat it means
unauthorized: invalid api key (HTTP 401)The key is wrong or is not an admin key. Copy the Admin key from your cluster's API keys tab.
Unfortunately, the gRPC health check against Weaviate could not be completed.The client reached REST but not gRPC. Check the endpoint format for your client: the Go and C# clients want a bare hostname, without https://. On a self-hosted instance, also check that port 50051 is published and not blocked.
no vectorizer found for class "Movie"You ran a nearText query against a collection that has no vectorizer. Create the collection with a vectorizer, or query with nearVector and supply the vector yourself.
no api key found neither in request header: ... nor in environment variable under ...The model provider key never reached Weaviate. Pass it in the connection headers, as in the model provider examples.
Con004: The connection to Weaviate was not closed properly.The script finished without closing the client. Call client.close(), or use a context manager.

Step 1: Create a collection & import data​

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.

py docs  API docs
More infoCode snippets in the documentation reflect the latest client library and Weaviate Database version. Check the Release notes for specific versions.

If a snippet doesn't work or you have feedback, please open a GitHub issue.
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:

# Step 1.2: Create a collection
movies = client.collections.create(
name="Movie",
vector_config=Configure.Vectors.text2vec_weaviate(), # Configure the Weaviate Embeddings vectorizer
)

# Step 1.3: Import three objects
data_objects = [
{"title": "The Matrix", "description": "A computer hacker learns about the true nature of reality and his role in the war against its controllers.", "genre": "Science Fiction"},
{"title": "Spirited Away", "description": "A young girl becomes trapped in a mysterious world of spirits and must find a way to save her parents and return home.", "genre": "Animation"},
{"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.", "genre": "Fantasy"},
]

movies = client.collections.use("Movie")
movies.data.ingest(data_objects)

print(f"Imported & vectorized {len(movies)} objects into the Movie collection")
import weaviate, { WeaviateClient, ApiKey, vectors } from '@weaviate/node';

// 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),
}
);

// Step 1.2: Create a collection
const movies = await client.collections.create({
name: 'Movie',
vectorizers: vectors.text2VecWeaviate(),
});

// Step 1.3: Import three objects
const dataObjects = [
{ title: 'The Matrix', description: 'A computer hacker learns about the true nature of reality and his role in the war against its controllers.', genre: 'Science Fiction' },
{ title: 'Spirited Away', description: 'A young girl becomes trapped in a mysterious world of spirits and must find a way to save her parents and return home.', genre: 'Animation' },
{ 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.', genre: 'Fantasy' },
];

const movieCollection = client.collections.get('Movie');
await movieCollection.data.ingest(
dataObjects.map((properties) => ({ properties }))
);

console.log(`Imported & vectorized ${dataObjects.length} objects into the Movie collection`);

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

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

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)
}

// Step 1.2: Create a collection
classObj := &models.Class{
Class: "Movie",
Vectorizer: "text2vec-weaviate",
ModuleConfig: map[string]interface{}{
"generative-anthropic": map[string]interface{}{
"model": "claude-haiku-4-5",
},
},
}

err = client.Schema().ClassCreator().WithClass(classObj).Do(context.Background())
if err != nil {
panic(err)
}

// Step 1.3: Import three objects
dataObjects := []map[string]interface{}{
{
"title": "The Matrix",
"description": "A computer hacker learns about the true nature of reality and his role in the war against its controllers.",
"genre": "Science Fiction",
},
{
"title": "Spirited Away",
"description": "A young girl becomes trapped in a mysterious world of spirits and must find a way to save her parents and return home.",
"genre": "Animation",
},
{
"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.",
"genre": "Fantasy",
},
}

// Insert objects
objects := make([]*models.Object, len(dataObjects))
for i, obj := range dataObjects {
objects[i] = &models.Object{
Class: "Movie",
Properties: obj,
}
}

_, err = client.Batch().ObjectsBatcher().WithObjects(objects...).Do(context.Background())
if err != nil {
panic(err)
}

fmt.Printf("Imported & vectorized %d objects into the Movie collection\n", len(dataObjects))
Go client v6

This tab uses the v6 Go client. It vectorizes data with Weaviate Embeddings (the text2vec-weaviate module). Collection-level generative (RAG) configuration is not yet available in the client, so it is omitted here (see Step 3).

package main

import (
"context"
"fmt"
"os"

weaviate "github.com/weaviate/weaviate-go-client/v6"
"github.com/weaviate/weaviate-go-client/v6/collections"
"github.com/weaviate/weaviate-go-client/v6/data"
wembed "github.com/weaviate/weaviate-go-client/v6/modules/weaviate"
)

func main() {
ctx := context.Background()

// Best practice: store your credentials in environment variables.
// Step 1.1: Connect to your Weaviate Cloud instance.
client, err := weaviate.NewWeaviateCloud(
ctx,
os.Getenv("WEAVIATE_URL"), // e.g. "my-cluster.weaviate.cloud"
os.Getenv("WEAVIATE_API_KEY"), // an admin API key
)
if err != nil {
// handle error
panic(err)
}
defer client.Close()

// Step 1.2: Create a collection vectorized by Weaviate Embeddings
// (the text2vec-weaviate module).
if _, err := client.Collections.Create(ctx, collections.Collection{
Name: "Movie",
Properties: []collections.Property{
{Name: "title", DataType: collections.DataTypeText},
{Name: "description", DataType: collections.DataTypeText},
{Name: "genre", DataType: collections.DataTypeText},
},
Vectors: map[string]collections.VectorConfig{
"default": {Vectorizer: wembed.Text2Vec{}},
},
}); err != nil {
// handle error
panic(err)
}

// Step 1.3: Import a few objects. Weaviate Embeddings vectorizes each on import.
if _, err := client.Collections.Use("Movie").Data.Insert(ctx,
&data.Object{Properties: map[string]any{
"title": "The Matrix",
"description": "A computer hacker learns about the true nature of reality and his role in the war against its controllers.",
"genre": "Science Fiction",
}},
&data.Object{Properties: map[string]any{
"title": "Spirited Away",
"description": "A young girl becomes trapped in a mysterious world of spirits and must find a way to save her parents and return home.",
"genre": "Animation",
}},
&data.Object{Properties: map[string]any{
"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.",
"genre": "Fantasy",
}},
); err != nil {
// handle error
panic(err)
}

fmt.Println("Imported & vectorized 3 objects into the Movie collection")
}
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);
// Step 1.2: Create a collection
client.collections.create(collectionName,
col -> col.vectorConfig(VectorConfig.text2vecWeaviate())
// Define properties for the collection
.properties(Property.text("title"), Property.text("description"),
Property.text("genre")));

// Step 1.3: Import three objects
List<Map<String, Object>> dataObjects = List.of(Map.of("title",
"The Matrix", "description",
"A computer hacker learns about the true nature of reality and his role in the war against its controllers.",
"genre", "Science Fiction"),
Map.of("title", "Spirited Away", "description",
"A young girl becomes trapped in a mysterious world of spirits and must find a way to save her parents and return home.",
"genre", "Animation"),
Map.of("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.",
"genre", "Fantasy"));

// Insert the objects using server-side batching
CollectionHandle<Map<String, Object>> movies =
client.collections.use(collectionName);
BatchContext<Map<String, Object>> batch = movies.batch.start();
// Closing the batch sends the remaining objects and waits for the results
try (batch) {
for (Map<String, Object> properties : dataObjects) {
batch.add(
WeaviateObject.<Map<String, Object>>of(o -> o.properties(properties)));
}
}

if (batch.numberOfErrors() > 0) {
System.err
.println("Number of failed imports: " + batch.numberOfErrors());
} else {
System.out.println("Imported & vectorized " + dataObjects.size()
+ " objects into the Movie collection");
}
} finally {
if (client != null) {
client.close(); // Free up resources
}
}
}
}
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);

// Create a collection
var movies = await client.Collections.Create(
new CollectionCreateParams
{
Name = collectionName,
VectorConfig = Configure.Vector("default", v => v.Text2VecWeaviate()),
// Define properties for the collection
Properties =
[
Property.Text("title"),
Property.Text("description"),
Property.Text("genre"),
],
}
);

// Import three objects
var dataObjects = new List<object>
{
new
{
title = "The Matrix",
description = "A computer hacker learns about the true nature of reality and his role in the war against its controllers.",
genre = "Science Fiction",
},
new
{
title = "Spirited Away",
description = "A young girl becomes trapped in a mysterious world of spirits and must find a way to save her parents and return home.",
genre = "Animation",
},
new
{
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.",
genre = "Fantasy",
},
};

// Insert the objects using server-side batching
var insertResponse = await movies.Batch.InsertMany(dataObjects);

if (insertResponse.HasErrors)
{
Console.WriteLine($"Errors during import: {insertResponse.Errors}");
}
else
{
Console.WriteLine(
$"Imported & vectorized {insertResponse.Count} objects into the Movie collection"
);
}
}
}
}
For production use

This step shows vector search on its own. For most applications, start with hybrid search, which combines vector search with lexical or keyword (BM25) search for a "best of both worlds" performance.

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.

py docs  API docs
More infoCode snippets in the documentation reflect the latest client library and Weaviate Database version. Check the Release notes for specific versions.

If a snippet doesn't work or you have feedback, please open a GitHub issue.
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
response = movies.query.near_text(
query="sci-fi",
limit=2
)

for obj in response.objects:
print(json.dumps(obj.properties, indent=2)) # Inspect the results
import weaviate, { WeaviateClient, ApiKey } from '@weaviate/node';

// 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
const response = await movies.query.nearText(
'sci-fi',
{
limit: 2,
}
);

for (const obj of response.objects) {
console.log(JSON.stringify(obj.properties, null, 2)); // Inspect the results
}

await client.close(); // Free up resources
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
title := graphql.Field{Name: "title"}
description := graphql.Field{Name: "description"}
genre := graphql.Field{Name: "genre"}

nearText := client.GraphQL().NearTextArgBuilder().
WithConcepts([]string{"sci-fi"})

result, err := client.GraphQL().Get().
WithClassName("Movie").
WithNearText(nearText).
WithLimit(2).
WithFields(title, description, genre).
Do(context.Background())

if err != nil {
panic(err)
}

// Inspect the results
if result.Errors != nil {
fmt.Printf("Error: %v\n", result.Errors)
return
}

data := result.Data["Get"].(map[string]interface{})
movies := data["Movie"].([]interface{})

for _, movie := range movies {
jsonData, err := json.MarshalIndent(movie, "", " ")
if err != nil {
panic(err)
}
fmt.Println(string(jsonData))
}
package main

import (
"context"
"fmt"
"os"

weaviate "github.com/weaviate/weaviate-go-client/v6"
"github.com/weaviate/weaviate-go-client/v6/query"
)

func main() {
ctx := context.Background()

// Step 2.1: Connect to your Weaviate Cloud instance.
client, err := weaviate.NewWeaviateCloud(
ctx,
os.Getenv("WEAVIATE_URL"), // e.g. "my-cluster.weaviate.cloud"
os.Getenv("WEAVIATE_API_KEY"), // an admin API key
)
if err != nil {
// handle error
panic(err)
}
defer client.Close()

// Step 2.2: Semantic (vector) search. Weaviate Embeddings vectorizes the query
// text server-side and returns the closest matches.
movies := client.Collections.Use("Movie")
response, err := movies.Query.NearText(ctx, query.NearText{
Concepts: []string{"science fiction movie"},
Limit: 2,
})
if err != nil {
// handle error
panic(err)
}
for _, obj := range response.Objects {
fmt.Printf("%v\n", obj.Properties)
}
}
import io.weaviate.client6.v1.api.WeaviateClient;
import io.weaviate.client6.v1.api.collections.CollectionHandle;
import com.fasterxml.jackson.databind.ObjectMapper; // For pretty-printing JSON

import 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
}
}
}
}
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 }
)
);
}
}
}
}
Example response
{
"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)​

Requirement: Claude API key

For Retrieval Augmented Generation (RAG) in this step, you will need a Claude API key. You can also use another generative model provider instead.

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).

py docs  API docs
More infoCode snippets in the documentation reflect the latest client library and Weaviate Database version. Check the Release notes for specific versions.

If a snippet doesn't work or you have feedback, please open a GitHub issue.
import os
import weaviate
from weaviate.classes.generate import GenerativeConfig

# Best practice: store your credentials in environment variables
weaviate_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 instance
with 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
import weaviate, { WeaviateClient, ApiKey, generativeParameters } from '@weaviate/node';

// Best practice: store your credentials in environment variables
const 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 instance
const client: WeaviateClient = await weaviate.connectToWeaviateCloud(
weaviateUrl,
{
authCredentials: new ApiKey(weaviateApiKey),
headers: { 'X-Anthropic-Api-Key': anthropicApiKey },
}
);

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

// Step 2.3: Perform RAG with on NearText results
const 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 results

await client.close(); // Free up resources
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_HOST")
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)
Go client v6

Generative (RAG) queries are not yet available in the v6 Go client.

// Coming soon
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
}
}
}
}
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));
}
}
}
Example response
🕶️ 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

Step 4: Query Agent​

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.

py docs  API docs
More infoCode snippets in the documentation reflect the latest client library and Weaviate Database version. Check the Release notes for specific versions.

If a snippet doesn't work or you have feedback, please open a GitHub issue.
import os
import weaviate
from weaviate.agents.query import QueryAgent

# 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: 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']}")
import weaviate, { WeaviateClient, ApiKey } from '@weaviate/node';
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:

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

Next steps​

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


Questions and feedback​