Azure AI Search integration
Este conteúdo não está disponível em sua língua ainda.
Azure AI Search is an enterprise-ready information retrieval system for your heterogeneous content that you ingest into a search index, and surface to users through queries and apps. It comes with a comprehensive set of advanced search technologies, built for high-performance applications at any scale. The Aspire Azure AI Search integration enables you to connect to Azure AI Search services from your applications.
Hosting integration
Section titled “Hosting integration”The Aspire Azure AI Search hosting integration models the search service as the AzureSearchResource type. To access this type and APIs for expressing them within your AppHost project, install the 📦 Aspire.Hosting.Azure.Search NuGet package:
aspire add azure-searchA CLI Aspire é interativa; escolhe o resultado apropriado quando solicitado:
Select an integration to add:
> azure-search (Aspire.Hosting.Azure.Search)> Other results listed as selectable options...#:package Aspire.Hosting.Azure.Search@*<PackageReference Include="Aspire.Hosting.Azure.Search" Version="*" />Add an Azure AI Search resource
Section titled “Add an Azure AI Search resource”To add an Azure AI Search resource to your AppHost project, call the AddAzureSearch method providing a name:
var builder = DistributedApplication.CreateBuilder(args);
var search = builder.AddAzureSearch("search");
builder.AddProject<Projects.ExampleProject>() .WithReference(search);
// After adding all resources, run the app...The preceding code adds an Azure AI Search resource named search to the AppHost project. The WithReference method passes the connection information to the ExampleProject project.
Connect to an existing Azure AI Search instance
Section titled “Connect to an existing Azure AI Search instance”You might have an existing Azure AI Search service that you want to connect to. You can chain a call to annotate that your AzureSearchResource is an existing resource:
var builder = DistributedApplication.CreateBuilder(args);
var existingSearchName = builder.AddParameter("existingSearchName");var existingSearchResourceGroup = builder.AddParameter("existingSearchResourceGroup");
var search = builder.AddAzureSearch("search") .AsExisting(existingSearchName, existingSearchResourceGroup);
builder.AddProject<Projects.ExampleProject>() .WithReference(search);
// After adding all resources, run the app...For more information on treating Azure AI Search resources as existing resources, see Use existing Azure resources.
Provisioning-generated Bicep
Section titled “Provisioning-generated Bicep”If you’re new to Bicep, it’s a domain-specific language for defining Azure resources. With , you don’t need to write Bicep by hand; instead, the provisioning APIs generate Bicep for you. When you publish your app, the generated Bicep is output alongside the manifest file. When you add an Azure AI Search resource, Bicep is generated to provision the search service with appropriate defaults.
@description('The location for the resource(s) to be deployed.')param location string = resourceGroup().location
resource search 'Microsoft.Search/searchServices@2023-11-01' = { name: take('search-${uniqueString(resourceGroup().id)}', 60) location: location properties: { hostingMode: 'default' disableLocalAuth: true partitionCount: 1 replicaCount: 1 } sku: { name: 'basic' } tags: { 'aspire-resource-name': 'search' }}
output connectionString string = 'Endpoint=https://${search.name}.search.windows.net'
output name string = search.nameThe preceding Bicep is a module that provisions an Azure AI Search service resource. Additionally, role assignments are created for the Azure resource in a separate module:
@description('The location for the resource(s) to be deployed.')param location string = resourceGroup().location
param search_outputs_name string
param principalType string
param principalId string
resource search 'Microsoft.Search/searchServices@2023-11-01' existing = { name: search_outputs_name}
resource search_SearchIndexDataContributor 'Microsoft.Authorization/roleAssignments@2022-04-01' = { name: guid(search.id, principalId, subscriptionResourceId('Microsoft.Authorization/roleDefinitions', '8ebe5a00-799e-43f5-93ac-243d3dce84a7')) properties: { principalId: principalId roleDefinitionId: subscriptionResourceId('Microsoft.Authorization/roleDefinitions', '8ebe5a00-799e-43f5-93ac-243d3dce84a7') principalType: principalType } scope: search}
resource search_SearchServiceContributor 'Microsoft.Authorization/roleAssignments@2022-04-01' = { name: guid(search.id, principalId, subscriptionResourceId('Microsoft.Authorization/roleDefinitions', '7ca78c08-252a-4471-8644-bb5ff32d4ba0')) properties: { principalId: principalId roleDefinitionId: subscriptionResourceId('Microsoft.Authorization/roleDefinitions', '7ca78c08-252a-4471-8644-bb5ff32d4ba0') principalType: principalType } scope: search}The generated Bicep is a starting point and is influenced by changes to the provisioning infrastructure in C#. Customizations to the Bicep file directly will be overwritten, so make changes through the C# provisioning APIs to ensure they are reflected in the generated files.
Customize provisioning infrastructure
Section titled “Customize provisioning infrastructure”All Aspire Azure resources are subclasses of the AzureProvisioningResource type. This type enables the customization of the generated Bicep by providing a fluent API to configure the Azure resources using the ConfigureInfrastructure API:
var builder = DistributedApplication.CreateBuilder(args);
builder.AddAzureSearch("search") .ConfigureInfrastructure(infra => { var searchService = infra.GetProvisionableResources() .OfType<SearchService>() .Single();
searchService.PartitionCount = 6; searchService.ReplicaCount = 3; searchService.SearchSkuName = SearchServiceSkuName.Standard3; searchService.Tags.Add("ExampleKey", "Example value"); });The preceding code:
- Chains a call to the
ConfigureInfrastructureAPI:- The
infraparameter is an instance of theAzureResourceInfrastructuretype. - The provisionable resources are retrieved by calling the
GetProvisionableResourcesmethod. - The single
SearchServiceresource is retrieved.- The
PartitionCountis set to6. - The
ReplicaCountis set to3. - The
SearchSkuNameis set toStandard3. - A tag is added to the Cognitive Services resource with a key of
ExampleKeyand a value ofExample value.
- The
- The
There are many more configuration options available to customize the Search resource. For more information, see Azure.Provisioning customization.
Client integration
Section titled “Client integration”The Aspire Azure AI Search client integration is used to connect to an Azure AI Search service using the SearchIndexClient. To get started with the Aspire Azure AI Search client integration, install the 📦 Aspire.Azure.Search.Documents NuGet package.
dotnet add package Aspire.Azure.Search.Documents#:package Aspire.Azure.Search.Documents@*<PackageReference Include="Aspire.Azure.Search.Documents" Version="*" />Add an Azure AI Search index client
Section titled “Add an Azure AI Search index client”In the Program.cs file of your client-consuming project, call the AddAzureSearchClient extension method on any IHostApplicationBuilder to register a SearchIndexClient class for use via the dependency injection container. The method takes a connection name parameter.
builder.AddAzureSearchClient(connectionName: "search");After adding the SearchIndexClient, you can retrieve the client instance using dependency injection. For example, to retrieve the client instance from an example service:
public class ExampleService(SearchIndexClient indexClient){ // Use indexClient}You can also retrieve a SearchClient which can be used for querying, by calling the GetSearchClient method:
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; }}For more information, see:
- Azure AI Search client library for .NET samples using the
SearchIndexClient. - Dependency injection in .NET for details on dependency injection.
Add keyed Azure AI Search index client
Section titled “Add keyed Azure AI Search index client”There might be situations where you want to register multiple SearchIndexClient instances with different connection names. To register keyed Azure AI Search clients, call the AddKeyedAzureSearchClient method:
builder.AddKeyedAzureSearchClient(name: "images");builder.AddKeyedAzureSearchClient(name: "documents");Then you can retrieve the client instances using dependency injection. For example, to retrieve the clients from a service:
public class ExampleService( [KeyedService("images")] SearchIndexClient imagesClient, [KeyedService("documents")] SearchIndexClient documentsClient){ // Use clients...}For more information, see Keyed services in .NET.
Configuration
Section titled “Configuration”The Azure AI Search Documents library provides multiple options to configure the Azure AI Search connection based on the requirements and conventions of your project. Either an Endpoint or a ConnectionString is required to be supplied.
Use a connection string
Section titled “Use a connection string”A connection can be constructed from the Keys and Endpoint tab with the format Endpoint={endpoint};Key={key};. You can provide the name of the connection string when calling builder.AddAzureSearchClient():
builder.AddAzureSearchClient("searchConnectionName");The connection string is retrieved from the ConnectionStrings configuration section. Two connection formats are supported:
Account endpoint
Section titled “Account endpoint”The recommended approach is to use an Endpoint, which works with the AzureSearchSettings.Credential property to establish a connection. If no credential is configured, the DefaultAzureCredential is used.
{ "ConnectionStrings": { "search": "https://{search_service}.search.windows.net/" }}Connection string
Section titled “Connection string”Alternatively, a connection string with key can be used, however; it’s not the recommended approach:
{ "ConnectionStrings": { "search": "Endpoint=https://{search_service}.search.windows.net/;Key={account_key};" }}Use configuration providers
Section titled “Use configuration providers”The Azure AI Search library supports Microsoft.Extensions.Configuration. It loads the AzureSearchSettings and SearchClientOptions from configuration by using the Aspire:Azure:Search:Documents key. Example :::no-loc text=“appsettings.json”::: that configures some of the options:
{ "Aspire": { "Azure": { "Search": { "Documents": { "DisableTracing": false } } } }}For the complete Azure AI Search Documents client integration JSON schema, see Aspire.Azure.Search.Documents/ConfigurationSchema.json.
Use named configuration
Section titled “Use named configuration”The Azure AI Search library supports named configuration, which allows you to configure multiple instances of the same resource type with different settings. The named configuration uses the connection name as a key under the main configuration section.
{ "Aspire": { "Azure": { "Search": { "Documents": { "search1": { "Endpoint": "https://mysearch1.search.windows.net/", "DisableTracing": false }, "search2": { "Endpoint": "https://mysearch2.search.windows.net/", "DisableTracing": true } } } } }}In this example, the search1 and search2 connection names can be used when calling AddAzureSearchClient:
builder.AddAzureSearchClient("search1");builder.AddAzureSearchClient("search2");Named configuration takes precedence over the top-level configuration. If both are provided, the settings from the named configuration override the top-level settings.
Use inline delegates
Section titled “Use inline delegates”You can also pass the Action<AzureSearchSettings> configureSettings delegate to set up some or all the options inline, for example to disable tracing from code:
builder.AddAzureSearchClient( "searchConnectionName", static settings => settings.DisableTracing = true);You can also set up the SearchClientOptions using the optional Action<IAzureClientBuilder<SearchIndexClient, SearchClientOptions>> configureClientBuilder parameter of the AddAzureSearchClient method. For example, to set the client ID for this client:
builder.AddAzureSearchClient( "searchConnectionName", configureClientBuilder: builder => builder.ConfigureOptions( static options => options.Diagnostics.ApplicationId = "CLIENT_ID"));The Azure AI Search Documents integration implements a single health check that calls the GetServiceStatisticsAsync method on the SearchIndexClient to verify that the service is available.
Aspire integrations automatically set up Logging, Tracing, and Metrics configurations, which are sometimes known as the pillars of observability. For more information about integration observability and telemetry, see Aspire integrations overview. Depending on the backing service, some integrations may only support some of these features. For example, some integrations support logging and tracing, but not metrics. Telemetry features can also be disabled using the techniques presented in the Configuration section.
Logging
Section titled “Logging”The Azure AI Search Documents integration uses the following log categories:
AzureAzure.CoreAzure.Identity
Tracing
Section titled “Tracing”The Azure AI Search Documents integration emits tracing activities using OpenTelemetry when interacting with the search service.