Connect to Azure AI Search
Dieser Inhalt ist noch nicht in deiner Sprache verfügbar.
This page describes how consuming apps connect to an Azure AI Search resource that’s already modeled in your AppHost. For the AppHost API surface — adding a search resource, connecting to existing services, customizing provisioning, and more — see Azure AI Search Hosting integration.
When you reference an Azure AI Search 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 Azure AI Search client integration for automatic dependency injection, health checks, and telemetry.
Connection properties
Section titled “Connection properties”Aspire exposes each property as an environment variable named [RESOURCE]_[PROPERTY]. For instance, the Endpoint property of a resource called search becomes SEARCH_ENDPOINT.
The Azure AI Search resource exposes the following connection properties:
| Property Name | Description |
|---|---|
Endpoint | The HTTPS endpoint of the Azure AI Search service: https://{name}.search.windows.net |
ApiKey | The admin API key (only available when using key-based connection strings, not role-based auth) |
Example connection string (role-based access, default):
Endpoint=https://mysearch.search.windows.netExample connection string (key-based access):
Endpoint=https://mysearch.search.windows.net;Key={account_key}Connect from your app
Section titled “Connect from your app”Pick the language your consuming app is written in. Each example assumes your AppHost adds an Azure AI Search resource named search and references it from the consuming app.
For C# apps, the recommended approach is the Aspire Azure AI Search client integration. It registers a SearchIndexClient through dependency injection and adds health checks and telemetry automatically. If you’d rather read environment variables directly, see the Read environment variables section at the end of this tab.
Install the client integration
Section titled “Install the client integration”Install the 📦 Aspire.Azure.Search.Documents NuGet package in the client-consuming project:
dotnet add package Aspire.Azure.Search.Documents#:package Aspire.Azure.Search.Documents@*<PackageReference Include="Aspire.Azure.Search.Documents" Version="*" />Add the Azure Search index client
Section titled “Add the Azure Search index client”In Program.cs, call AddAzureSearchClient on your IHostApplicationBuilder to register a SearchIndexClient:
builder.AddAzureSearchClient(connectionName: "search");Resolve the client through dependency injection:
public class ExampleService(SearchIndexClient indexClient){ // Use indexClient...}You can also retrieve a SearchClient for querying by calling GetSearchClient on the injected SearchIndexClient:
public class ExampleService(SearchIndexClient indexClient){ public async Task<long> GetDocumentCountAsync( string indexName, CancellationToken cancellationToken) { var searchClient = indexClient.GetSearchClient(indexName);
var documentCountResponse = await searchClient.GetDocumentCountAsync( cancellationToken);
return documentCountResponse.Value; }}Add keyed Azure Search index clients
Section titled “Add keyed Azure Search index clients”To register multiple SearchIndexClient instances with different connection names, use AddKeyedAzureSearchClient:
builder.AddKeyedAzureSearchClient(name: "catalog");builder.AddKeyedAzureSearchClient(name: "documents");Then resolve each instance by key:
public class ExampleService( [FromKeyedServices("catalog")] SearchIndexClient catalogClient, [FromKeyedServices("documents")] SearchIndexClient documentsClient){ // Use clients...}For more information, see .NET dependency injection: Keyed services.
Configuration
Section titled “Configuration”The Aspire Azure AI Search 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 AddAzureSearchClient.
For role-based access (recommended), provide just the endpoint URL:
{ "ConnectionStrings": { "search": "https://mysearch.search.windows.net/" }}For key-based access, provide the full connection string:
{ "ConnectionStrings": { "search": "Endpoint=https://mysearch.search.windows.net/;Key={account_key};" }}Configuration providers. The client integration supports Microsoft.Extensions.Configuration. It loads AzureSearchSettings from appsettings.json (or any other configuration source) by using the Aspire:Azure:Search:Documents key:
{ "Aspire": { "Azure": { "Search": { "Documents": { "DisableTracing": false } } } }}For the complete Azure AI Search Documents client integration JSON schema, see Aspire.Azure.Search.Documents/ConfigurationSchema.json.
Named configuration. To configure multiple instances, use the connection name as a key:
{ "Aspire": { "Azure": { "Search": { "Documents": { "search1": { "Endpoint": "https://mysearch1.search.windows.net/", "DisableTracing": false }, "search2": { "Endpoint": "https://mysearch2.search.windows.net/", "DisableTracing": true } } } } }}Named configuration takes precedence over top-level configuration when both are provided.
Inline delegates. Pass an Action<AzureSearchSettings> to configure settings inline:
builder.AddAzureSearchClient( "search", static settings => settings.DisableTracing = true);You can also configure the SearchClientOptions using the configureClientBuilder parameter:
builder.AddAzureSearchClient( "search", configureClientBuilder: builder => builder.ConfigureOptions( static options => options.Diagnostics.ApplicationId = "CLIENT_ID"));Client integration health checks
Section titled “Client integration health checks”The Azure AI Search client integration adds a health check that calls GetServiceStatisticsAsync on the SearchIndexClient to verify that the service is available. 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
Section titled “Observability and telemetry”The Aspire Azure AI Search client integration automatically configures logging, tracing, and metrics through OpenTelemetry.
Logging categories:
AzureAzure.CoreAzure.Identity
Tracing activities:
- The integration emits tracing activities using OpenTelemetry when interacting with the search service.
Any of these telemetry features can be disabled through the configuration options above.
Read environment variables in C#
Section titled “Read environment variables in C#”If you prefer not to use the Aspire client integration, you can read the Aspire-injected endpoint from the environment and use the 📦 Azure.Search.Documents package directly with DefaultAzureCredential:
using Azure;using Azure.Identity;using Azure.Search.Documents.Indexes;
var endpoint = new Uri(Environment.GetEnvironmentVariable("SEARCH_ENDPOINT")!);
// Use DefaultAzureCredential for role-based access (recommended)var indexClient = new SearchIndexClient(endpoint, new DefaultAzureCredential());
// Use AzureKeyCredential for key-based access// var apiKey = Environment.GetEnvironmentVariable("SEARCH_APIKEY");// var indexClient = new SearchIndexClient(endpoint, new AzureKeyCredential(apiKey!));Use the azure-sdk-for-go package for Azure AI Search:
go get github.com/Azure/azure-sdk-for-go/sdk/search/azsearchgo get github.com/Azure/azure-sdk-for-go/sdk/azidentityRead the injected environment variable and connect:
package main
import ( "os" "github.com/Azure/azure-sdk-for-go/sdk/azidentity" "github.com/Azure/azure-sdk-for-go/sdk/search/azsearch")
func main() { // Read the Aspire-injected endpoint endpoint := os.Getenv("SEARCH_ENDPOINT")
// Use DefaultAzureCredential for role-based access (recommended) cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { panic(err) }
client, err := azsearch.NewIndexesClient(endpoint, cred, nil) if err != nil { panic(err) }
_ = client}For key-based access, use azsearch.NewIndexesClientWithKey:
package main
import ( "os" "github.com/Azure/azure-sdk-for-go/sdk/search/azsearch")
func main() { endpoint := os.Getenv("SEARCH_ENDPOINT") apiKey := os.Getenv("SEARCH_APIKEY")
client, err := azsearch.NewIndexesClientWithKey(endpoint, apiKey, nil) if err != nil { panic(err) }
_ = client}Install the azure-search-documents package:
pip install azure-search-documents azure-identityRead the injected environment variable and connect:
import osfrom azure.identity import DefaultAzureCredentialfrom azure.search.documents.indexes import SearchIndexClient
# Read the Aspire-injected endpointendpoint = os.getenv("SEARCH_ENDPOINT")
# Use DefaultAzureCredential for role-based access (recommended)credential = DefaultAzureCredential()client = SearchIndexClient(endpoint=endpoint, credential=credential)For key-based access, use AzureKeyCredential:
import osfrom azure.core.credentials import AzureKeyCredentialfrom azure.search.documents.indexes import SearchIndexClient
endpoint = os.getenv("SEARCH_ENDPOINT")api_key = os.getenv("SEARCH_APIKEY")
client = SearchIndexClient(endpoint=endpoint, credential=AzureKeyCredential(api_key))Install the @azure/search-documents package:
npm install @azure/search-documents @azure/identityRead the injected environment variables and connect:
import { SearchIndexClient } from '@azure/search-documents';import { DefaultAzureCredential } from '@azure/identity';
// Read Aspire-injected connection propertiesconst endpoint = process.env.SEARCH_ENDPOINT!;
// Use DefaultAzureCredential for role-based access (recommended)const client = new SearchIndexClient(endpoint, new DefaultAzureCredential());For key-based access, use AzureKeyCredential:
import { SearchIndexClient, AzureKeyCredential } from '@azure/search-documents';
const endpoint = process.env.SEARCH_ENDPOINT!;const apiKey = process.env.SEARCH_APIKEY!;
const client = new SearchIndexClient(endpoint, new AzureKeyCredential(apiKey));