# Connect to Milvus

<Image
  src={milvusIcon}
  alt="Milvus logo"
  width={100}
  height={100}
  class:list={'float-inline-left icon'}
  data-zoom-off
/>

This page describes how consuming apps connect to a Milvus resource that's already modeled in your AppHost. For the AppHost API surface — adding a Milvus server, databases, Attu GUI, data volumes, API key parameters, and more — see [Milvus Hosting integration](../milvus-host/).

When you reference a Milvus resource from your AppHost, Aspire injects the connection information into the consuming app as environment variables. Your app can either read those environment variables directly — the pattern works the same from any language — or, in C#, use the Aspire Milvus client integration for automatic dependency injection and health checks.

## Connection properties

Aspire exposes each property as an environment variable named `[RESOURCE]_[PROPERTY]`. For instance, the `Uri` property of a resource called `milvusdb` becomes `MILVUSDB_URI`.

### Milvus server

The Milvus server resource exposes the following connection properties:

| Property Name | Description |
| ------------- | ----------- |
| `Host`        | The hostname or IP address of the Milvus server |
| `Port`        | The gRPC port exposed by the Milvus server |
| `Token`       | The authentication token, with the format `root:{ApiKey}` |
| `Uri`         | The gRPC endpoint URI, with the format `http://{Host}:{Port}` |

**Example connection strings:**

```
Uri: http://localhost:19530
Token: root:Milvus
```

### Milvus database

The Milvus database resource inherits all properties from its parent server resource and adds:

| Property Name  | Description              |
| -------------- | ------------------------ |
| `DatabaseName` | The Milvus database name |

## Connect from your app

Pick the language your consuming app is written in. Each example assumes your AppHost adds a Milvus server named `milvus`, a database named `milvusdb`, and references the database from the consuming app.

For C# apps, the recommended approach is the Aspire Milvus client integration. It registers a [`MilvusClient`](https://github.com/milvus-io/milvus-sdk-csharp) through dependency injection and adds health checks automatically. If you'd rather read environment variables directly, see the [Read environment variables](#read-environment-variables-in-c) section at the end of this tab.

#### Install the client integration

Install the [📦 Aspire.Milvus.Client](https://www.nuget.org/packages/Aspire.Milvus.Client) NuGet package in the client-consuming project:

<InstallDotNetPackage packageName="Aspire.Milvus.Client" />
**Caution:** The Milvus client integration is currently in preview.

#### Add the Milvus client

In _Program.cs_, call `AddMilvusClient` on your `IHostApplicationBuilder` to register a `MilvusClient`:

```csharp title="C# — Program.cs"
builder.AddMilvusClient(connectionName: "milvusdb");
```
**Tip:** The `connectionName` must match the Milvus database resource name from the AppHost. For more information, see [Add Milvus server and database resources](../milvus-host/#add-milvus-server-and-database-resources).

Resolve the client through dependency injection:

```csharp title="C# — ExampleService.cs"
public class ExampleService(MilvusClient client)
{
    // Use client...
}
```

#### Add keyed Milvus clients

To register multiple `MilvusClient` instances with different connection names, use `AddKeyedMilvusClient`:

```csharp title="C# — Program.cs"
builder.AddKeyedMilvusClient(name: "mainDb");
builder.AddKeyedMilvusClient(name: "loggingDb");
```

Then resolve each instance by key:

```csharp title="C# — ExampleService.cs"
public class ExampleService(
    [FromKeyedServices("mainDb")] MilvusClient mainDbClient,
    [FromKeyedServices("loggingDb")] MilvusClient loggingDbClient)
{
    // Use clients...
}
```

For more information on keyed services, see [.NET dependency injection: Keyed services](https://learn.microsoft.com/dotnet/core/extensions/dependency-injection#keyed-services).

#### Configuration

The Aspire Milvus client integration offers multiple ways to provide configuration.

**Connection strings.** When using a connection string from the `ConnectionStrings` configuration section, pass the connection name to `AddMilvusClient`:

```csharp title="C# — Program.cs"
builder.AddMilvusClient("milvusdb");
```

The connection string is resolved from the `ConnectionStrings` section:

```json title="JSON — appsettings.json"
{
  "ConnectionStrings": {
    "milvusdb": "Endpoint=http://localhost:19530/;Key=root:Non-default-P@ssw0rd"
  }
}
```

**Configuration providers.** The client integration supports `Microsoft.Extensions.Configuration`. It loads `MilvusSettings` from _appsettings.json_ (or any other configuration source) by using the `Aspire:Milvus:Client` key:

```json title="JSON — appsettings.json"
{
  "Aspire": {
    "Milvus": {
      "Client": {
        "Endpoint": "http://localhost:19530/",
        "Database": "milvusdb",
        "Key": "root:Non-default-P@ssw0rd",
        "DisableHealthChecks": false
      }
    }
  }
}
```

**Inline delegates.** Pass an `Action<MilvusSettings>` to configure settings inline, for example to set the API key from code:

```csharp title="C# — Program.cs"
builder.AddMilvusClient(
    "milvusdb",
    static settings => settings.Key = "root:Non-default-P@ssw0rd");
```

#### Configuration options

The following options are available:

| Name                  | Description |
| --------------------- | ----------- |
| `Endpoint`            | The endpoint URI of the Milvus server to connect to |
| `Database`            | The name of the Milvus database |
| `Key`                 | The authentication key (format: `root:{password}`) |
| `DisableHealthChecks` | Whether the health check is disabled |

#### Client integration health checks

Aspire client integrations enable health checks by default. The Milvus client integration adds a health check that verifies the Milvus server is reachable and a connection can be established. The health check is wired into the `/health` HTTP endpoint, where all registered health checks must pass before the app is considered ready to accept traffic.

#### Observability and telemetry

The Aspire Milvus client integration configures the following logging categories:

- `Milvus.Client`

The Milvus integration doesn't currently emit tracing activities or metrics because they are not supported by the underlying `Milvus.Client` library.

#### Read environment variables in C\#

If you prefer not to use the Aspire client integration, you can read the Aspire-injected connection properties from the environment and create a `MilvusClient` directly using the [📦 Milvus.Client](https://www.nuget.org/packages/Milvus.Client/) NuGet package:

```csharp title="C# — Program.cs"
using Milvus.Client;

var host = Environment.GetEnvironmentVariable("MILVUSDB_HOST")!;
var port = int.Parse(Environment.GetEnvironmentVariable("MILVUSDB_PORT")!);
var token = Environment.GetEnvironmentVariable("MILVUSDB_TOKEN")!;
var database = Environment.GetEnvironmentVariable("MILVUSDB_DATABASENAME")!;

var client = new MilvusClient(host, port, database: database, apiKey: token);
```

Use the official [`milvus-io/milvus-sdk-go`](https://github.com/milvus-io/milvus-sdk-go) client:

```bash title="Terminal"
go get github.com/milvus-io/milvus-sdk-go/v2
```

Read the injected environment variables and connect:

```go title="Go — main.go"
package main

import (
    "context"
    "fmt"
    "os"
    "strconv"

    "github.com/milvus-io/milvus-sdk-go/v2/client"
)

func main() {
    // Read Aspire-injected connection properties
    host := os.Getenv("MILVUSDB_HOST")
    port := os.Getenv("MILVUSDB_PORT")
    token := os.Getenv("MILVUSDB_TOKEN")
    database := os.Getenv("MILVUSDB_DATABASENAME")

    portNum, _ := strconv.Atoi(port)

    ctx := context.Background()
    c, err := client.NewClient(ctx, client.Config{
        Address:  fmt.Sprintf("%s:%d", host, portNum),
        APIKey:   token,
        DBName:   database,
    })
    if err != nil {
        panic(err)
    }
    defer c.Close()

    // Use c to interact with Milvus...
}
```

Install [`pymilvus`](https://github.com/milvus-io/pymilvus), the official Python SDK for Milvus:

```bash title="Terminal"
pip install pymilvus
```

Read the injected environment variables and connect:

```python title="Python — app.py"
import os
from pymilvus import MilvusClient

# Read Aspire-injected connection properties
host = os.getenv("MILVUSDB_HOST")
port = os.getenv("MILVUSDB_PORT")
token = os.getenv("MILVUSDB_TOKEN")
database = os.getenv("MILVUSDB_DATABASENAME")

client = MilvusClient(
    uri=f"http://{host}:{port}",
    token=token,
    db_name=database,
)

# Use client to interact with Milvus...
```

Or use the connection URI directly:

```python title="Python — Connect with URI"
import os
from pymilvus import MilvusClient

client = MilvusClient(
    uri=os.getenv("MILVUSDB_URI"),
    token=os.getenv("MILVUSDB_TOKEN"),
)
```

Install [`@zilliz/milvus2-sdk-node`](https://github.com/milvus-io/milvus-sdk-node), the official Node.js SDK for Milvus:

```bash title="Terminal"
npm install @zilliz/milvus2-sdk-node
```

Read the injected environment variables and connect:

```typescript title="TypeScript — index.ts"
import { MilvusClient } from '@zilliz/milvus2-sdk-node';

// Read Aspire-injected connection properties
const client = new MilvusClient({
    address: `${process.env.MILVUSDB_HOST}:${process.env.MILVUSDB_PORT}`,
    token: process.env.MILVUSDB_TOKEN,
    database: process.env.MILVUSDB_DATABASENAME,
});

// Use client to interact with Milvus...
```

Or use the connection URI directly:

```typescript title="TypeScript — Connect with URI"
import { MilvusClient } from '@zilliz/milvus2-sdk-node';

const client = new MilvusClient({
    address: process.env.MILVUSDB_URI!,
    token: process.env.MILVUSDB_TOKEN,
});
```
**Tip:** If your app expects specific environment variable names different from the Aspire defaults, you can pass individual connection properties from the AppHost. See [Pass custom environment variables](../milvus-host/#pass-custom-environment-variables) in the Hosting integration reference.