### Full Example: Cloud Setup with Authentication and Timeouts
Source: https://github.com/weaviate/csharp-client/blob/main/docs/CLIENT_INIT.md
A comprehensive example demonstrating the setup of the Weaviate C# client for a cloud deployment, including authentication using an API key, setting various timeouts (default, init, insert, query), retry policy, and basic operations like checking readiness, getting metadata, inserting data, and querying.
```csharp
using Weaviate.Client;
using System;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
// Create a configured client
var client = await new WeaviateClientBuilder()
.Cloud(
restEndpoint: "my-cluster.weaviate.cloud",
apiKey: Environment.GetEnvironmentVariable("WEAVIATE_API_KEY")
)
.WithDefaultTimeout(TimeSpan.FromSeconds(30))
.WithInitTimeout(TimeSpan.FromSeconds(5))
.WithInsertTimeout(TimeSpan.FromSeconds(60))
.WithQueryTimeout(TimeSpan.FromSeconds(120))
.WithRetryPolicy(new RetryPolicy(maxRetries: 3))
.BuildAsync();
try
{
// Check if the instance is ready
bool isReady = await client.IsReady();
Console.WriteLine($"Weaviate ready: {isReady}");
// Get meta information
var meta = await client.GetMeta();
Console.WriteLine($"Weaviate version: {meta.Version}");
// Work with collections
var articleCollection = client.Collections.Get("Article");
// Insert data
var article = new { title = "Hello World", content = "..." };
var id = await articleCollection.Data.Insert(article);
Console.WriteLine($"Inserted article with ID: {id}");
// Query data
var results = await articleCollection.Query
.NearText("science");
foreach (var obj in results.Objects)
{
Console.WriteLine($"Found: {obj.Properties}");
}
}
catch (Exception ex)
{
Console.Error.WriteLine($"Error: {ex.Message}");
}
finally
{
client.Dispose();
}
}
}
```
--------------------------------
### Start Weaviate Locally using Docker
Source: https://github.com/weaviate/csharp-client/blob/main/src/Example/README.md
Provides the Docker command to run a Weaviate instance locally. This setup includes necessary port mappings and enables essential modules like `text2vec-weaviate`, serving as a prerequisite for most client examples.
```bash
docker run -d \
-p 8080:8080 \
-p 50051:50051 \
-e ENABLE_MODULES=text2vec-weaviate \
-e DEFAULT_VECTORIZER_MODULE=text2vec-weaviate \
cr.weaviate.io/semitechnologies/weaviate:latest
```
--------------------------------
### Example: Local Development Setup with Timeouts
Source: https://github.com/weaviate/csharp-client/blob/main/docs/CLIENT_INIT.md
Provides a simple example for setting up the Weaviate C# client for local development, configuring timeouts for initialization, insertion, and queries, while connecting to a local Weaviate instance.
```csharp
var client = await new WeaviateClientBuilder()
.Local(hostname: "localhost")
.WithDefaultTimeout(TimeSpan.FromSeconds(30))
.WithInitTimeout(TimeSpan.FromSeconds(10))
.WithInsertTimeout(TimeSpan.FromSeconds(60))
.WithQueryTimeout(TimeSpan.FromSeconds(120))
.BuildAsync();
```
--------------------------------
### Complete RBAC Example with Weaviate C# Client
Source: https://github.com/weaviate/csharp-client/blob/main/docs/RBAC_API_USAGE.md
A comprehensive example demonstrating the full lifecycle of RBAC operations using the Weaviate C# client. This includes creating roles and users, assigning roles, verifying permissions, and cleaning up resources.
```csharp
using Weaviate.Client;
using Weaviate.Client.Models;
var adminKey = Environment.GetEnvironmentVariable("WEAVIATE_ADMIN_API_KEY") ?? "admin-key";
var client = WeaviateClientBuilder.Local(restPort: 8092, grpcPort: 50063)
.WithCredentials(Auth.ApiKey(adminKey))
.Build();
if (!await client.IsReady()) throw new Exception("Weaviate not ready");
// Create a role with permissions
var roleName = $"demo-role-{Guid.NewGuid():N}";
var role = await client.Roles.Create(roleName, new[]
{
new Permissions.Roles { Read = true },
new Permissions.Collections { Read = true }
});
Console.WriteLine($"Created role: {role.Name}");
// Create a database user
var userId = $"demo-user-{Guid.NewGuid():N}";
var userKey = await client.Users.Db.Create(userId);
Console.WriteLine($"Created user {userId} with API key");
// Assign role to user
await client.Users.Db.AssignRoles(userId, roleName);
Console.WriteLine($"Assigned role {roleName} to user {userId}");
// Verify role assignment
var userRoles = await client.Users.Db.GetRoles(userId);
Console.WriteLine($"User roles: {string.Join(", ", userRoles.Select(r => r.Name))}");
// Check specific permission
var hasPermission = await client.Roles.HasPermission(roleName, new Permissions.Roles { Read = true });
Console.WriteLine($"Role has read_roles permission: {hasPermission}");
// List all role assignments for this user
var assignments = await client.Roles.GetUserAssignments(roleName);
Console.WriteLine($"Users with role {roleName}: {assignments.Count()}");
// Cleanup
await client.Users.Db.RevokeRoles(userId, roleName);
await client.Roles.Delete(roleName);
await client.Users.Db.Delete(userId);
Console.WriteLine("Cleanup complete");
```
--------------------------------
### Run Weaviate C# Examples via Command Line
Source: https://github.com/weaviate/csharp-client/blob/main/src/Example/README.md
Execute specific Weaviate C# client examples using the dotnet CLI by providing the example name as an argument. This allows for targeted testing and demonstration of different functionalities.
```bash
dotnet run --project src/Example -- traditional
dotnet run --project src/Example -- di
dotnet run --project src/Example -- multiple
dotnet run --project src/Example -- configs
dotnet run --project src/Example -- configuration
dotnet run --project src/Example -- lazy
dotnet run --project src/Example -- connect
```
--------------------------------
### Configure Multiple Vector Configurations for a Collection in C#
Source: https://github.com/weaviate/csharp-client/blob/main/docs/VECTORIZER_CONFIGURATION.md
Illustrates how to define a collection with multiple, named vector configurations. This example shows setting up text, image, and multi-modal vectorizers for a single collection, allowing for diverse retrieval strategies.
```csharp
var collection = await client.Collections.Create(
new CollectionConfig
{
Name = "Article",
Properties = new[]
{
Property.Text("title"),
Property.Text("content"),
Property.Blob("image")
},
VectorConfig = new[]
{
// Text embeddings
Configure.Vectors.Text2VecOpenAI(model: "text-embedding-3-small")
.New("text_vec", "title", "content"),
// Image embeddings
Configure.Vectors.Img2VecNeural(imageFields: ["image"])
.New("image_vec"),
// Multi-modal embeddings
Configure.Vectors.Multi2VecClip(
textFields: ["title"],
imageFields: ["image"]
).New("clip_vec")
}
}
);
```
--------------------------------
### Start Weaviate Server for Integration Tests
Source: https://github.com/weaviate/csharp-client/blob/main/README.md
This snippet shows how to start a local Weaviate server instance using a provided shell script. It defaults to version 1.31.0 but can be configured to use any version greater than or equal to 1.31.0 for integration testing.
```bash
./ci/start_weaviate.sh # uses 1.31.0
# or explicitly
./ci/start_weaviate.sh 1.32.7 # any version >= 1.31.0
```
--------------------------------
### Install Weaviate C# Client via .NET CLI
Source: https://github.com/weaviate/csharp-client/blob/main/README.md
This snippet shows how to add the Weaviate C# client package to your project using the .NET CLI. Ensure you have the .NET SDK installed and your project is initialized.
```bash
dotnet add package Weaviate.Client --version 0.0.1-beta.4
```
--------------------------------
### Weaviate C# Client Copy Replication Example
Source: https://github.com/weaviate/csharp-client/blob/main/docs/REPLICATION_IMPLEMENTATION_SUMMARY.md
Example demonstrating how to perform a 'Copy' replication operation using the Weaviate C# client. It shows the creation of a `ReplicateRequest` specifying source and target nodes, collection, shard, and type, followed by initiating the replication and waiting for its completion. The output checks the final state of the replication.
```csharp
var request = new ReplicateRequest(
Collection: "MyCollection",
Shard: "shard-abc123",
SourceNode: "node1",
TargetNode: "node2",
Type: ReplicationType.Copy
);
var tracker = await client.Cluster.Replicate(request);
var result = await tracker.WaitForCompletion();
if (result.Status.State == ReplicationOperationState.Ready)
{
Console.WriteLine("Replication complete!");
}
```
--------------------------------
### Weaviate C# Client Move Replication Example
Source: https://github.com/weaviate/csharp-client/blob/main/docs/REPLICATION_IMPLEMENTATION_SUMMARY.md
Example demonstrating how to perform a 'Move' replication operation using the Weaviate C# client. It illustrates the synchronous waiting pattern by calling `ReplicateSync`, which immediately returns the result after the operation is completed. This is suitable when immediate confirmation of the move operation is required.
```csharp
var request = new ReplicateRequest(
Collection: "MyCollection",
Shard: "shard-abc123",
SourceNode: "node1",
TargetNode: "node2",
Type: ReplicationType.Move
);
// Synchronous wait pattern
var result = await client.Cluster.ReplicateSync(request);
```
--------------------------------
### Configure Single Vectorizer with Flat Index
Source: https://github.com/weaviate/csharp-client/blob/main/docs/VECTORIZER_CONFIGURATION.md
Details the configuration of a single vectorizer using a Flat index, which is optimized for certain scenarios and supports only BQ (Binary Quantization). The example includes setting the distance metric and quantization parameters such as cache and rescore limit.
```csharp
var config = Configure.Vectors.Text2VecTransformers()
.New(
name: "flat_vec",
indexConfig: new VectorIndex.Flat
{
Distance = VectorIndexConfig.VectorDistance.Cosine
},
quantizerConfig: new VectorIndex.Quantizers.BQ
{
Cache = true,
RescoreLimit = 200
},
sourceProperties: ["text"]
);
```
--------------------------------
### Multi2VecBind Configuration
Source: https://github.com/weaviate/csharp-client/blob/main/docs/VECTORIZER_CONFIGURATION.md
Configure the Multi2VecBind model for multi-modal embeddings using ImageBind.
```APIDOC
## Multi2VecBind Configuration
### Description
ImageBind for multiple modalities including audio, depth, images, IMU, text, thermal, and video.
### Method
Configure.Vectors.Multi2VecBind
### Parameters
#### Query Parameters
- **audioFields** (string[]) - Optional - Array of property names containing audio data.
- **depthFields** (string[]) - Optional - Array of property names containing depth map data.
- **imageFields** (string[]) - Optional - Array of property names containing image data.
- **imuFields** (string[]) - Optional - Array of property names containing IMU data.
- **textFields** (string[]) - Optional - Array of property names containing text data.
- **thermalFields** (string[]) - Optional - Array of property names containing thermal image data.
- **videoFields** (string[]) - Optional - Array of property names containing video data.
- **vectorizeCollectionName** (bool) - Optional - Whether to vectorize the collection name.
### Request Example (All Modalities)
```csharp
var config = Configure.Vectors.Multi2VecBind(
audioFields: ["audio"],
depthFields: ["depth_map"],
imageFields: ["photo"],
imuFields: ["imu_data"],
textFields: ["description"],
thermalFields: ["thermal_image"],
videoFields: ["video"],
vectorizeCollectionName: false
).New("default");
```
### Request Example (Weighted Fields)
```csharp
var config = Configure.Vectors.Multi2VecBind(
audioFields: new WeightedFields { ("audio", 0.4) },
textFields: new WeightedFields { ("description", 0.6) }
).New("default");
```
**Wire Format:** `multi2vec-bind`
**Type:** Single Vector
**Supported Modalities:**
- Audio
- Depth images
- Images
- IMU (Inertial Measurement Unit) data
- Text
- Thermal images
- Video
```
--------------------------------
### Multi2VecJinaAI Configuration
Source: https://github.com/weaviate/csharp-client/blob/main/docs/VECTORIZER_CONFIGURATION.md
Configure the Multi2VecJinaAI model for multi-modal embeddings using Jina AI.
```APIDOC
## Multi2VecJinaAI Configuration
### Description
Jina AI multi-modal embeddings.
### Method
Configure.Vectors.Multi2VecJinaAI
### Parameters
#### Query Parameters
- **model** (string) - Optional - The Jina AI model to use (default: "jina-clip-v1").
- **baseURL** (string) - Optional - The base URL for the Jina AI API.
- **dimensions** (int) - Optional - The desired dimensionality of the embeddings.
- **imageFields** (string[]) - Optional - Array of property names containing images.
- **textFields** (string[]) - Optional - Array of property names containing text.
- **vectorizeCollectionName** (bool) - Optional - Whether to vectorize the collection name.
### Request Example
```csharp
var config = Configure.Vectors.Multi2VecJinaAI(
model: "jina-clip-v1",
baseURL: null,
dimensions: 768,
imageFields: ["image"],
textFields: ["description"],
vectorizeCollectionName: true
).New("default");
```
**Wire Format:** `multi2vec-jinaai`
**Type:** Single Vector
```
--------------------------------
### Multi2VecClip Configuration
Source: https://github.com/weaviate/csharp-client/blob/main/docs/VECTORIZER_CONFIGURATION.md
Configure the Multi2VecClip model for text and image embeddings using OpenAI CLIP.
```APIDOC
## Multi2VecClip Configuration
### Description
OpenAI CLIP for text and images. Handles multiple modalities.
### Method
Configure.Vectors.Multi2VecClip
### Parameters
#### Query Parameters
- **inferenceUrl** (string) - Required - The URL for the inference endpoint.
- **imageFields** (string[]) - Required - An array of property names containing images.
- **textFields** (string[]) - Required - An array of property names containing text.
- **vectorizeCollectionName** (bool) - Optional - Whether to vectorize the collection name.
### Request Example (Standard)
```csharp
var config = Configure.Vectors.Multi2VecClip(
inferenceUrl: "http://localhost:8080",
imageFields: ["image"],
textFields: ["title", "description"],
vectorizeCollectionName: false
).New("default");
```
### Request Example (Weighted Fields)
```csharp
var weightedFields = new WeightedFields
{
("title", 0.7),
("description", 0.3)
};
var config = Configure.Vectors.Multi2VecClip(
imageFields: new WeightedFields { ("image", 1.0) },
textFields: weightedFields
).New("default");
```
**Wire Format:** `multi2vec-clip`
**Type:** Single Vector
```
--------------------------------
### Mixing Single and Multi-Vector Configurations
Source: https://github.com/weaviate/csharp-client/blob/main/docs/VECTORIZER_CONFIGURATION.md
Demonstrates how to combine both regular single-vector and multi-vector configurations within a collection.
```APIDOC
## POST /v1/ தொகுப்புகள்
### Description
Creates a collection that includes both standard single-vector and multi-vector configurations.
### Method
POST
### Endpoint
/v1/collections
### Parameters
#### Request Body
- **Name** (string) - Required - The name of the collection.
- **Properties** (array) - Required - Schema defining the properties of the collection.
- **VectorConfig** (object) - Required - An object mapping vector names to their configurations.
- **`[vectorName]`** (object) - Configuration for a specific vector.
- **Vectorizer** (string) - Required - The vectorizer type.
- **Model** (string) - Optional - The model to use.
- **SourceProperties** (string[]) - Optional - Properties for single-vector embeddings.
- **IndexConfig** (object) - Optional - Index configuration, especially for multi-vectors.
- **MultiVector** (object) - Required for multi-vector configurations.
- **Aggregation** (string) - Optional - Aggregation method.
- **Encoding** (object) - Optional - Encoding configuration.
- **Input** (string[]) - Optional - Source properties for multi-vector inputs.
### Request Example
```json
{
"Name": "Document",
"Properties": [
{"name": "content", "dataType": ["text"]}
],
"VectorConfig": {
"regular": {
"Vectorizer": "text2vec-openai"
},
"colbert": {
"Vectorizer": "text2multivec-jinaai",
"Model": "jina-colbert-v2",
"IndexConfig": {
"MultiVector": {
"Aggregation": "MaxSim",
"Encoding": {}
}
},
"Input": ["content"]
}
}
}
```
### Response
#### Success Response (200)
Returns the details of the created collection.
#### Response Example
```json
{
"message": "Collection created successfully."
}
```
```
--------------------------------
### Multi2VecAWS Configuration
Source: https://github.com/weaviate/csharp-client/blob/main/docs/VECTORIZER_CONFIGURATION.md
Configure the Multi2VecAWS model for multi-modal embeddings using AWS Bedrock.
```APIDOC
## Multi2VecAWS Configuration
### Description
AWS Bedrock multi-modal embeddings.
### Method
Configure.Vectors.Multi2VecAWS
### Parameters
#### Query Parameters
- **region** (string) - Required - The AWS region.
- **model** (string) - Optional - The Bedrock model to use (default: "amazon.titan-embed-image-v1").
- **dimensions** (int) - Optional - The desired dimensionality of the embeddings.
- **imageFields** (string[]) - Optional - Array of property names containing images.
- **textFields** (string[]) - Optional - Array of property names containing text.
- **vectorizeCollectionName** (bool) - Optional - Whether to vectorize the collection name.
### Request Example
```csharp
var config = Configure.Vectors.Multi2VecAWS(
region: "us-east-1",
model: "amazon.titan-embed-image-v1",
dimensions: null,
imageFields: ["image"],
textFields: ["caption"],
vectorizeCollectionName: true
).New("default");
```
**Wire Format:** `multi2vec-aws`
**Type:** Single Vector
```
--------------------------------
### Multi2VecNvidia Configuration
Source: https://github.com/weaviate/csharp-client/blob/main/docs/VECTORIZER_CONFIGURATION.md
Configure the Multi2VecNvidia model for multi-modal embeddings using NVIDIA.
```APIDOC
## Multi2VecNvidia Configuration
### Description
NVIDIA multi-modal embeddings.
### Method
Configure.Vectors.Multi2VecNvidia
### Parameters
#### Query Parameters
- **baseURL** (string) - Optional - The base URL for the NVIDIA API.
- **model** (string) - Optional - The NVIDIA model to use (default: "nvidia/nv-embedqa-e5-v5").
- **properties** (string[]) - Optional - The properties to use for embedding (e.g., ["text", "image"]).
- **truncate** (bool) - Optional - Whether to truncate input.
### Request Example
```csharp
var config = Configure.Vectors.Multi2VecNvidia(
baseURL: null,
model: "nvidia/nv-embedqa-e5-v5",
properties: ["text", "image"],
truncate: false
).New("default");
```
**Wire Format:** `multi2vec-nvidia`
**Type:** Single Vector
```
--------------------------------
### Text2VecModel2Vec Configuration
Source: https://github.com/weaviate/csharp-client/blob/main/docs/VECTORIZER_CONFIGURATION.md
Configure the Text2VecModel2Vec embedding model for lightweight text embeddings.
```APIDOC
## Text2VecModel2Vec Configuration
### Description
Model2Vec embedding models provide lightweight embeddings.
### Method
Configure.Vectors.Text2VecModel2Vec
### Parameters
#### Query Parameters
- **inferenceURL** (string) - Required - The URL for the inference endpoint.
- **vectorizeCollectionName** (bool) - Optional - Whether to vectorize the collection name.
### Request Example
```csharp
var config = Configure.Vectors.Text2VecModel2Vec(
inferenceURL: "http://localhost:8080",
vectorizeCollectionName: false
).New("default", "text");
```
**Wire Format:** `text2vec-model2vec`
**Type:** Single Vector
```
--------------------------------
### Multi2VecGoogle Configuration
Source: https://github.com/weaviate/csharp-client/blob/main/docs/VECTORIZER_CONFIGURATION.md
Configure the Multi2VecGoogle model for multi-modal embeddings using Google Vertex AI.
```APIDOC
## Multi2VecGoogle Configuration
### Description
Google Vertex AI multi-modal embeddings.
### Method
Configure.Vectors.Multi2VecGoogle
### Parameters
#### Query Parameters
- **projectId** (string) - Required - GCP project ID.
- **location** (string) - Required - GCP location.
- **imageFields** (string[]) - Optional - Array of property names containing images.
- **textFields** (string[]) - Optional - Array of property names containing text.
- **videoFields** (string[]) - Optional - Array of property names containing video.
- **videoIntervalSeconds** (int) - Optional - Interval for video frame sampling.
- **model** (string) - Optional - The model to use (default: "multimodalembedding").
- **dimensions** (int) - Optional - The desired dimensionality of the embeddings.
- **vectorizeCollectionName** (bool) - Optional - Whether to vectorize the collection name.
### Request Example
```csharp
var config = Configure.Vectors.Multi2VecGoogle(
projectId: "my-project",
location: "us-central1",
imageFields: ["image"],
textFields: ["title", "description"],
videoFields: ["video"],
videoIntervalSeconds: 2,
model: "multimodalembedding",
dimensions: 512,
vectorizeCollectionName: true
).New("default");
```
**Wire Format:** `multi2vec-palm`
**Type:** Single Vector
```
--------------------------------
### Multi2VecCohere Configuration
Source: https://github.com/weaviate/csharp-client/blob/main/docs/VECTORIZER_CONFIGURATION.md
Configure the Multi2VecCohere model for multi-modal embeddings using Cohere.
```APIDOC
## Multi2VecCohere Configuration
### Description
Cohere multi-modal embeddings.
### Method
Configure.Vectors.Multi2VecCohere
### Parameters
#### Query Parameters
- **baseURL** (string) - Optional - The base URL for the Cohere API.
- **imageFields** (string[]) - Optional - Array of property names containing images.
- **model** (string) - Optional - The Cohere model to use (default: "embed-english-v3.0").
- **dimensions** (int) - Optional - The desired dimensionality of the embeddings.
- **textFields** (string[]) - Optional - Array of property names containing text.
- **truncate** (string) - Optional - Truncation strategy for input (e.g., "END").
- **vectorizeCollectionName** (bool) - Optional - Whether to vectorize the collection name.
### Request Example
```csharp
var config = Configure.Vectors.Multi2VecCohere(
baseURL: null,
imageFields: ["photo"],
model: "embed-english-v3.0",
dimensions: null,
textFields: ["title", "content"],
truncate: "END",
vectorizeCollectionName: true
).New("default");
```
**Wire Format:** `multi2vec-cohere`
**Type:** Single Vector
```
--------------------------------
### Multi2VecVoyageAI Configuration
Source: https://github.com/weaviate/csharp-client/blob/main/docs/VECTORIZER_CONFIGURATION.md
Configure the Multi2VecVoyageAI model for multi-modal embeddings using VoyageAI.
```APIDOC
## Multi2VecVoyageAI Configuration
### Description
VoyageAI multi-modal embeddings.
### Method
Configure.Vectors.Multi2VecVoyageAI
### Parameters
#### Query Parameters
- **baseURL** (string) - Optional - The base URL for the VoyageAI API.
- **imageFields** (string[]) - Optional - Array of property names containing images.
- **model** (string) - Optional - The VoyageAI model to use (default: "voyage-multimodal-3").
- **textFields** (string[]) - Optional - Array of property names containing text.
- **truncate** (bool) - Optional - Whether to truncate input.
- **vectorizeCollectionName** (bool) - Optional - Whether to vectorize the collection name.
### Request Example
```csharp
var config = Configure.Vectors.Multi2VecVoyageAI(
baseURL: null,
imageFields: ["photo"],
model: "voyage-multimodal-3",
textFields: ["caption"],
truncate: false,
vectorizeCollectionName: true
).New("default");
```
**Wire Format:** `multi2vec-voyageai`
**Type:** Single Vector
```
--------------------------------
### Text2VecJinaAI Configuration
Source: https://github.com/weaviate/csharp-client/blob/main/docs/VECTORIZER_CONFIGURATION.md
Configures the Text2VecJinaAI embedding model for leveraging Jina AI's embedding models.
```APIDOC
## Text2VecJinaAI
### Description
Configures Jina AI embedding models.
### Method
N/A (Configuration)
### Endpoint
N/A (Configuration)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```csharp
var config = Configure.Vectors.Text2VecJinaAI(
model: "jina-embeddings-v2-base-en",
baseURL: null,
dimensions: 768,
vectorizeCollectionName: true
).New("default", "text");
```
### Response
#### Success Response (200)
N/A (Configuration)
#### Response Example
N/A (Configuration)
```
--------------------------------
### Create and Restore Backups (C#)
Source: https://context7.com/weaviate/csharp-client/llms.txt
This example demonstrates how to create and restore Weaviate backups using the C# client. It shows creating backups to both the local filesystem and an S3 bucket, specifying collections to include, and monitoring the backup process. It also details restoring a backup, optionally including specific collections. The code requires the Weaviate C# client and configured storage backends.
```csharp
using Weaviate.Client;
using Weaviate.Client.Models;
var client = await Connect.Local();
// Create backup to filesystem
var createOp = await client.Backups.Create(new BackupCreateRequest(
id: "my-backup-2024",
backend: BackupBackend.Filesystem(path: "/backups"),
Include: new[] { "Cat", "Article" } // Only backup specific collections
));
// Monitor backup progress
while (!createOp.IsCompleted)
{
Console.WriteLine($"Backup status: {createOp.Current.Status}");
await Task.Delay(1000);
}
await createOp.WaitForCompletion();
Console.WriteLine($"Backup completed: {createOp.Current.Status}");
// Create backup to S3
var s3CreateOp = await client.Backups.Create(new BackupCreateRequest(
id: "s3-backup-2024",
backend: BackupBackend.S3(bucket: "my-backup-bucket", path: "weaviate-backups/")
));
await s3CreateOp.WaitForCompletion();
Console.WriteLine("S3 backup completed");
// Restore from backup
var restoreOp = await client.Backups.Restore(new BackupRestoreRequest(
id: "my-backup-2024",
backend: BackupBackend.Filesystem(path: "/backups"),
Include: new[] { "Cat" } // Restore only specific collections
));
await restoreOp.WaitForCompletion();
Console.WriteLine($"Restore completed: {restoreOp.Current.Status}");
```
--------------------------------
### Get Operation with History
Source: https://github.com/weaviate/csharp-client/blob/main/docs/REPLICATION_API_USAGE.md
Retrieve a specific operation and its complete status transition history. Useful for debugging and understanding the lifecycle of an operation.
```APIDOC
## GET /v1/cluster/replications/{operationId}?includeHistory=true
### Description
Retrieve a specific operation including its full status transition history.
### Method
GET
### Endpoint
`/v1/cluster/replications/{operationId}`
### Parameters
#### Path Parameters
- **operationId** (string) - Required - The unique identifier of the operation.
#### Query Parameters
- **includeHistory** (boolean) - Optional - If true, includes the status transition history.
### Response
#### Success Response (200)
- **operation** (object) - Details about the replication operation.
- **id** (string) - The unique identifier of the operation.
- **collection** (string) - The name of the collection being replicated.
- **shard** (string) - The name of the shard being replicated.
- **type** (string) - The type of replication operation.
- **status** (object) - The current status of the operation.
- **state** (string) - The current state of the operation.
- **whenStarted** (string) - The timestamp when this state started.
- **statusHistory** (array) - An array of historical status objects.
- **state** (string) - The historical state of the operation.
- **whenStarted** (string) - The timestamp when this historical state started.
- **errors** (array) - An array of errors that occurred during this state (if any).
- **message** (string) - The error message.
#### Response Example
```json
{
"id": "op-12345",
"collection": "Users",
"shard": "shard-main",
"type": "COPY",
"status": {
"state": "READY",
"whenStarted": "2023-10-27T10:05:00Z"
},
"statusHistory": [
{
"state": "REGISTERED",
"whenStarted": "2023-10-27T10:00:00Z"
},
{
"state": "HYDRATING",
"whenStarted": "2023-10-27T10:01:00Z"
},
{
"state": "READY",
"whenStarted": "2023-10-27T10:05:00Z"
}
]
}
```
```
--------------------------------
### Get Operation Details
Source: https://github.com/weaviate/csharp-client/blob/main/docs/REPLICATION_API_USAGE.md
Retrieve details of a specific replication operation by its ID. This includes collection, shard, type, and current status.
```APIDOC
## GET /v1/cluster/replications/{operationId}
### Description
Retrieve a specific operation by ID.
### Method
GET
### Endpoint
`/v1/cluster/replications/{operationId}`
### Parameters
#### Path Parameters
- **operationId** (string) - Required - The unique identifier of the operation.
### Response
#### Success Response (200)
- **operation** (object) - Details about the replication operation.
- **collection** (string) - The name of the collection being replicated.
- **shard** (string) - The name of the shard being replicated.
- **type** (string) - The type of replication operation (e.g., COPY, MOVE).
- **status** (object) - The current status of the operation.
- **state** (string) - The current state of the operation (e.g., REGISTERED, HYDRATING, READY, CANCELLED).
#### Response Example
```json
{
"collection": "Articles",
"shard": "shard-abc123",
"type": "COPY",
"status": {
"state": "HYDRATING",
"whenStarted": "2023-10-27T10:00:00Z"
}
}
```
```
--------------------------------
### Quick Local Weaviate Connection with Defaults and Customization
Source: https://github.com/weaviate/csharp-client/blob/main/docs/CLIENT_INIT.md
Demonstrates using the `Connect.Local()` helper for quick connections to a local Weaviate instance. It shows connecting with default settings, custom credentials and ports, and specific timeout configurations using `TimeSpan`.
```csharp
// Connect to local Weaviate with defaults
var client = await Connect.Local();
// Connect to local with custom credentials
var client = await Connect.Local(
credentials: Auth.ApiKey("your-api-key"),
hostname: "localhost",
restPort: 8080,
grpcPort: 50051,
useSsl: false
);
// Connect with custom timeouts
var client = await Connect.Local(
credentials: Auth.ApiKey("your-api-key"),
hostname: "localhost",
defaultTimeout: TimeSpan.FromSeconds(30),
initTimeout: TimeSpan.FromSeconds(5),
insertTimeout: TimeSpan.FromSeconds(60),
queryTimeout: TimeSpan.FromSeconds(120)
);
```
--------------------------------
### Connect Weaviate using Helper Methods
Source: https://github.com/weaviate/csharp-client/blob/main/src/Example/README.md
Illustrates the use of traditional `Connect.Local()` and `Connect.Cloud()` methods for creating a Weaviate client. These methods provide backward compatibility, are fully asynchronous, and offer a simple way to create a client instance, suitable for quick scripts and simple applications.
```csharp
// Local
var client = await Connect.Local();
// Cloud
var client = await Connect.Cloud(
clusterEndpoint: "my-cluster.weaviate.cloud",
apiKey: "my-api-key"
);
```
--------------------------------
### Get Operation Details with History
Source: https://github.com/weaviate/csharp-client/blob/main/docs/REPLICATION_API_USAGE.md
Retrieves a specific replication operation along with its complete status transition history. This is useful for debugging and understanding the lifecycle of an operation.
```csharp
var operation = await client.Cluster.Replications.Get(
operationId,
includeHistory: true
);
if (operation?.StatusHistory != null)
{
Console.WriteLine("Status History:");
foreach (var status in operation.StatusHistory)
{
Console.WriteLine($" - {status.State} at {status.WhenStarted}");
if (status.Errors?.Any() == true)
{
foreach (var error in status.Errors)
{
Console.WriteLine($" Error: {error.Message}");
}
}
}
}
```
--------------------------------
### List All Replication Operations
Source: https://github.com/weaviate/csharp-client/blob/main/docs/REPLICATION_API_USAGE.md
Retrieves a list of all currently tracked replication operations, including their full history. This is useful for getting an overview of all ongoing or recent replication tasks.
```csharp
var allOperations = await client.Cluster.Replications.ListAll();
foreach (var op in allOperations)
{
Console.WriteLine($"{op.Id}: {op.Collection}/{op.Shard} - {op.Status.State}");
}
```
--------------------------------
### Handle Weaviate Backup Conflict Exception (C#)
Source: https://github.com/weaviate/csharp-client/blob/main/docs/ERRORS.md
This exception is thrown when attempting to start a backup or restore operation while another backup or restore is already in progress. It prevents concurrent backup/restore tasks.
```csharp
public class WeaviateBackupConflictException : WeaviateServerException
{}
```
```csharp
try
{
await client.Backup.Create("backup-1", BackupStorage.Filesystem);
}
catch (WeaviateBackupConflictException ex)
{
Console.WriteLine("Another backup/restore is in progress");
// Wait and retry, or cancel the existing operation
}
```
--------------------------------
### Handle Client-Side WeaviateClientException in C#
Source: https://github.com/weaviate/csharp-client/blob/main/docs/ERRORS.md
Illustrates catching WeaviateClientException for client-side errors like invalid configuration or network issues. This helps in diagnosing problems related to the client's environment or setup.
```csharp
try
{
var client = WeaviateClientBuilder.Local(hostname: "invalid-host").Build();
await client.IsReady();
}
catch (WeaviateClientException ex)
{
Console.WriteLine($"Client error: {ex.Message}");
// Check configuration, network connectivity, etc.
}
```
--------------------------------
### Quick Weaviate Cloud Connection with API Key and Custom Timeouts
Source: https://github.com/weaviate/csharp-client/blob/main/docs/CLIENT_INIT.md
Shows how to quickly connect to a Weaviate Cloud instance using the `Connect.Cloud()` helper. It requires the `restEndpoint` and `apiKey`, and allows for setting custom `defaultTimeout` and `queryTimeout`.
```csharp
var client = await Connect.Cloud(
restEndpoint: "your-cluster.weaviate.cloud",
apiKey: "your-api-key"
);
// With custom timeouts
var client = await Connect.Cloud(
restEndpoint: "your-cluster.weaviate.cloud",
apiKey: "your-api-key",
defaultTimeout: TimeSpan.FromSeconds(30),
queryTimeout: TimeSpan.FromSeconds(120)
);
```
--------------------------------
### Configuring Different Weaviate Clients in C#
Source: https://github.com/weaviate/csharp-client/blob/main/src/Example/README.md
Demonstrates how to configure distinct settings for each named Weaviate client, including endpoints, SSL, authentication, timeouts, custom headers, and retry policies. Offers fine-grained control over client behavior.
```csharp
// Production: SSL + API key + short timeouts
services.AddWeaviateClient("production", options =>
{
options.RestEndpoint = "prod.weaviate.cloud";
options.UseSsl = true;
options.Credentials = Auth.ApiKey("key");
options.QueryTimeout = TimeSpan.FromSeconds(30);
});
// Local: No SSL, no auth, long timeouts for debugging
services.AddWeaviateClient("local", options =>
{
options.RestEndpoint = "localhost";
options.UseSsl = false;
options.Credentials = null;
options.QueryTimeout = TimeSpan.FromMinutes(5);
});
```
--------------------------------
### Get Operation Details by ID
Source: https://github.com/weaviate/csharp-client/blob/main/docs/REPLICATION_API_USAGE.md
Retrieves the details of a specific replication operation using its unique ID. This operation fetches basic information about the operation, such as the collection, shard, type, and current status.
```csharp
var operation = await client.Cluster.Replications.Get(operationId);
if (operation != null)
{
Console.WriteLine($"Collection: {operation.Collection}");
Console.WriteLine($"Shard: {operation.Shard}");
Console.WriteLine($"Type: {operation.Type}");
Console.WriteLine($"Status: {operation.Status.State}");
}
```
--------------------------------
### Get Specific Role Details
Source: https://github.com/weaviate/csharp-client/blob/main/docs/RBAC_API_USAGE.md
Retrieves details for a specific role by its name, including its permissions. It then prints the role's name and the count of its associated permissions. This function requires the role name as input.
```csharp
var role = await client.Roles.Get("viewer");
Console.WriteLine($"Role: {role.Name}, Permissions: {role.Permissions.Count}");
```
--------------------------------
### Install Weaviate C# Client via .csproj file
Source: https://github.com/weaviate/csharp-client/blob/main/README.md
This snippet demonstrates how to include the Weaviate C# client as a dependency in your .NET project by adding a PackageReference to your .csproj file. This is an alternative to using the .NET CLI.
```xml
```
--------------------------------
### Weaviate Client Integration Testing Setup
Source: https://github.com/weaviate/csharp-client/blob/main/docs/DEPENDENCY_INJECTION.md
Illustrates how to set up integration tests using the Weaviate C# client, implementing `IAsyncLifetime` for proper initialization and disposal. It shows how to connect to a local Weaviate instance, verify its readiness, and perform basic operations like fetching objects.
```csharp
public class MyIntegrationTests : IAsyncLifetime
{
private WeaviateClient _client = null!;
public async Task InitializeAsync()
{
// Setup test client
_client = await Connect.Local();
// Verify it's ready
Assert.True(_client.IsInitialized);
Assert.True(await _client.IsReady());
}
[Fact]
public async Task CanSearchCats()
{
var collection = _client.Collections.Use("Cat");
var results = await collection.Query.FetchObjects(limit: 10);
Assert.NotEmpty(results.Objects);
}
public async Task DisposeAsync()
{
_client?.Dispose();
}
}
```
--------------------------------
### Using Weighted Fields for Vectorizers in C#
Source: https://github.com/weaviate/csharp-client/blob/main/docs/VECTORIZER_CONFIGURATION.md
Demonstrates how to create and use WeightedFields objects for configuring vectorizers, allowing control over the influence of different properties in multi-modal embeddings. This includes examples using both tuple and explicit WeightedField syntax.
```csharp
// Create weighted fields
var weightedFields = new WeightedFields
{
("title", 0.7),
("description", 0.3)
};
// Or using tuple syntax
var fields = new WeightedFields
{
new WeightedField("title", 0.7),
new WeightedField("description", 0.3)
};
// Use in vectorizer configuration
var config = Configure.Vectors.Multi2VecClip(
textFields: weightedFields
).New("default");
```
--------------------------------
### Traditional Weaviate Client Usage in C#
Source: https://github.com/weaviate/csharp-client/blob/main/src/Example/README.md
Demonstrates classic Weaviate client usage without dependency injection. Includes creating a client, batch data insertion, basic queries, vector similarity search, and BM25 full-text search. Suitable for simple scripts and prototypes.
```csharp
var client = await Connect.Local();
var collection = client.Collections.Use("Cat");
var results = await collection.Query.FetchObjects(limit: 10);
```
--------------------------------
### Get Current User Information
Source: https://github.com/weaviate/csharp-client/blob/main/docs/RBAC_API_USAGE.md
Retrieves information about the currently authenticated user using the `Users.OwnInfo()` method. It displays the username, active status, and assigned role names. This is useful for verifying the current user's context.
```csharp
var me = await client.Users.OwnInfo();
Console.WriteLine($"Me: {me.Username}, Active={me.Active}, Roles={string.Join(",", me.Roles.Select(r => r.Name))}");
```
--------------------------------
### Get Cluster Nodes and Shards
Source: https://github.com/weaviate/csharp-client/blob/main/docs/REPLICATION_API_USAGE.md
Retrieves detailed information about Weaviate cluster nodes, including their shards, object counts, and vector indexing status. This data is essential for planning replication targets and understanding cluster topology.
```csharp
var nodes = await client.Cluster.Nodes.ListVerbose(collection: "Articles");
foreach (var node in nodes)
{
Console.WriteLine($"Node: {node.Name}");
foreach (var shard in node.Shards ?? Array.Empty())
{
Console.WriteLine($" Shard: {shard.Name}");
Console.WriteLine($" Objects: {shard.ObjectCount}");
Console.WriteLine($" Status: {shard.VectorIndexingStatus}");
}
}
```
--------------------------------
### Create and Get Database User
Source: https://github.com/weaviate/csharp-client/blob/main/docs/RBAC_API_USAGE.md
Creates a new database user with a generated ID and an API key using `client.Users.Db.Create()`. It then immediately retrieves the created user's details using `client.Users.Db.Get()`. This demonstrates user creation and retrieval.
```csharp
var newUserId = $"user-{Random.Shared.Next(1, 10_000)}";
var apiKey = await client.Users.Db.Create(newUserId);
var user = await client.Users.Db.Get(newUserId);
Console.WriteLine($"Created {user.UserId}, Active={user.Active}");
```
--------------------------------
### Configure Weaviate Clients with Helper Methods in C#
Source: https://github.com/weaviate/csharp-client/blob/main/docs/MULTIPLE_CLIENTS.md
Provides examples of using helper methods to register Weaviate clients for local development instances (specifying ports) and cloud instances (using cluster endpoint and API key). These methods simplify the configuration process.
```csharp
// For local instances
builder.Services.AddWeaviateClient(
name: "local",
hostname: "localhost",
restPort: 8080,
grpcPort: 50051
);
// For cloud instances
builder.Services.AddWeaviateCloudClient(
name: "prod",
clusterEndpoint: "prod.weaviate.cloud",
apiKey: "prod-key"
);
```
--------------------------------
### ASP.NET Core Web API Integration with Weaviate
Source: https://github.com/weaviate/csharp-client/blob/main/src/Example/README.md
Demonstrates integrating the Weaviate client into an ASP.NET Core Web API project using dependency injection. It shows how to configure the client in `Program.cs` or `Startup.cs` and how to inject and use the `WeaviateClient` in a controller for performing searches.
```csharp
// Program.cs or Startup.cs
builder.Services.AddWeaviateLocal(
hostname: builder.Configuration["Weaviate:Host"] ?? "localhost",
restPort: ushort.Parse(builder.Configuration["Weaviate:Port"] ?? "8080"),
eagerInitialization: true
);
// Controller
[ApiController]
[Route("[controller]")]
public class SearchController : ControllerBase
{
private readonly WeaviateClient _weaviate;
public SearchController(WeaviateClient weaviate)
{
_weaviate = weaviate;
}
[HttpGet]
public async Task Search([FromQuery] string query)
{
var collection = _weaviate.Collections.Use("Product");
var results = await collection.Query.BM25(query, limit: 10);
return Ok(results.Objects);
}
}
```
--------------------------------
### Using Connect Helpers for Weaviate Client Initialization
Source: https://github.com/weaviate/csharp-client/blob/main/docs/DEPENDENCY_INJECTION.md
Demonstrates the use of `Connect.Local()` and `Connect.Cloud()` helpers for asynchronously initializing the Weaviate client. These methods return a fully initialized client, utilize async initialization without blocking, and follow the standard initialization flow. They are suitable for console applications, scripts, and testing scenarios.
```csharp
// These work exactly as before - fully async, no blocking
var client = await Connect.Local();
var client = await Connect.Cloud("my-cluster.weaviate.cloud", "api-key");
// With timeouts
var client = await Connect.Local(
hostname: "localhost",
defaultTimeout: TimeSpan.FromSeconds(60),
queryTimeout: TimeSpan.FromSeconds(30)
);
```
--------------------------------
### Avoid Silently Swallowing Exceptions
Source: https://github.com/weaviate/csharp-client/blob/main/docs/ERRORS.md
Illustrates the negative impact of catching exceptions without proper handling, such as logging or re-throwing. The example shows a 'bad' case where a `WeaviateException` is caught and ignored, preventing debugging, contrasted with a 'good' case that logs the error and re-throws it.
```csharp
// ❌ Bad - silently swallows errors
try
{
await CriticalOperation();
}
catch (WeaviateException) { }
// ✅ Good - log and/or rethrow
try
{
await CriticalOperation();
}
catch (WeaviateException ex)
{
_logger.LogError(ex, "Critical operation failed");
throw;
}
```
--------------------------------
### Handle Specific HTTP Status Codes with Weaviate (C#)
Source: https://github.com/weaviate/csharp-client/blob/main/docs/ERRORS.md
This example shows how to handle specific HTTP status codes returned by the Weaviate server using the WeaviateUnexpectedStatusCodeException. It uses a switch statement to differentiate between common error codes like BadRequest, Unauthorized, and Forbidden.
```csharp
try
{
await client.SomeOperation();
}
catch (WeaviateUnexpectedStatusCodeException ex)
{
switch (ex.StatusCode)
{
case HttpStatusCode.BadRequest:
Console.WriteLine("Invalid request");
break;
case HttpStatusCode.Unauthorized:
Console.WriteLine("Authentication required");
break;
case HttpStatusCode.Forbidden:
Console.WriteLine("Permission denied");
break;
default:
Console.WriteLine($"Unexpected error: {ex.StatusCode}");
break;
}
}
```
--------------------------------
### Managing Multiple Weaviate Clients in C#
Source: https://github.com/weaviate/csharp-client/blob/main/src/Example/README.md
Illustrates how to register and use multiple named Weaviate clients concurrently within a C# application. Facilitates scenarios like multi-region deployments or multi-tenant architectures using IWeaviateClientFactory.
```csharp
// Register multiple clients
services.AddWeaviateClient("production", options => { ... });
services.AddWeaviateClient("staging", options => { ... });
services.AddWeaviateClient("local", "localhost", 8080, 50051);
// Use in service
public class MyService
{
private readonly IWeaviateClientFactory _factory;
public async Task ProcessAsync()
{
var prodClient = await _factory.GetClientAsync("production");
var stagingClient = await _factory.GetClientAsync("staging");
// Each has independent configuration
}
}
```