This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Note
Access to this page requires authorization. You can trysigning in orchanging directories.
Access to this page requires authorization. You can trychanging directories.
Azure AI Search (formerly known as "Azure Cognitive Search") is an AI-powered information retrieval platform that helps developers build rich search experiences and generative AI apps that combine large language models with enterprise data.
The Azure AI Search service is well suited for the following application scenarios:
Use the Azure.Search.Documents client library to:
Source code |Package (NuGet) |API reference documentation |REST API documentation |Product documentation |Samples
Install the Azure AI Search client library for .NET withNuGet:
dotnet add package Azure.Search.Documents
You need anAzure subscription and asearch service to use this package.
To create a new search service, you can use theAzure portal,Azure PowerShell, or theAzure CLI.Here's an example using the Azure CLI to create a free instance for getting started:
az search service create --name <mysearch> --resource-group <mysearch-rg> --sku free --location westus
Seechoosing a pricing tierfor more information about available options.
To interact with the search service, you'll need to create an instance of the appropriate client class:SearchClient
for searching indexed documents,SearchIndexClient
for managing indexes, orSearchIndexerClient
for crawling data sources and loading search documents into an index. To instantiate a client object, you'll need anendpoint andAzure roles or anAPI key. You can refer to the documentation for more information onsupported authenticating approaches with the search service.
An API key can be an easier approach to start with because it doesn't require pre-existing role assignments.
You can get theendpoint and anAPI key from the search service in theAzure portal. Please refer thedocumentation for instructions on how to get an API key.
Alternatively, you can use the followingAzure CLI command to retrieve the API key from the search service:
az search admin-key show --service-name <mysearch> --resource-group <mysearch-rg>
There are two types of keys used to access your search service:admin(read-write) andquery(read-only) keys. Restricting access andoperations in client apps is essential to safeguarding the search assets on yourservice. Always use a query key rather than an admin key for any queryoriginating from a client app.
Note: The example Azure CLI snippet above retrieves an admin key so it's easierto get started exploring APIs, but it should be managed carefully.
To instantiate theSearchClient
, you'll need theendpoint,API key andindex name:
string indexName = "nycjobs";// Get the service endpoint and API key from the environmentUri endpoint = new Uri(Environment.GetEnvironmentVariable("SEARCH_ENDPOINT"));string key = Environment.GetEnvironmentVariable("SEARCH_API_KEY");// Create a clientAzureKeyCredential credential = new AzureKeyCredential(key);SearchClient client = new SearchClient(endpoint, indexName, credential);
You can also create aSearchClient
,SearchIndexClient
, orSearchIndexerClient
using Microsoft Entra ID authentication. Your user or service principal must be assigned the "Search Index Data Reader" role.Using theDefaultAzureCredential you can authenticate a service using Managed Identity or a service principal, authenticate as a developer working on an application, and more all without changing code. Please refer thedocumentation for instructions on how to connect to Azure AI Search using Azure role-based access control (Azure RBAC).
Before you can use theDefaultAzureCredential
, or any credential type fromAzure.Identity, you'll first need toinstall the Azure.Identity package.
To useDefaultAzureCredential
with a client ID and secret, you'll need to set theAZURE_TENANT_ID
,AZURE_CLIENT_ID
, andAZURE_CLIENT_SECRET
environment variables; alternatively, you can pass those valuesto theClientSecretCredential
also in Azure.Identity.
Make sure you use the right namespace forDefaultAzureCredential
at the top of your source file:
using Azure.Identity;
Then you can create an instance ofDefaultAzureCredential
and pass it to a new instance of your client:
string indexName = "nycjobs";// Get the service endpoint from the environmentUri endpoint = new Uri(Environment.GetEnvironmentVariable("SEARCH_ENDPOINT"));DefaultAzureCredential credential = new DefaultAzureCredential();// Create a clientSearchClient client = new SearchClient(endpoint, indexName, credential);
To injectSearchClient
as a dependency in an ASP.NET Core app, first install the packageMicrosoft.Extensions.Azure
. Then register the client in theStartup.ConfigureServices
method:
public void ConfigureServices(IServiceCollection services){ services.AddAzureClients(builder => { builder.AddSearchClient(Configuration.GetSection("SearchClient")); }); services.AddControllers();}
To use the preceding code, add this to your configuration:
{ "SearchClient": { "endpoint": "https://<resource-name>.search.windows.net", "indexname": "nycjobs" }}
You'll also need to provide your resource key to authenticate the client, but you shouldn't be putting that information in the configuration. Instead, when in development, useUser-Secrets. Add the following tosecrets.json
:
{ "SearchClient": { "credential": { "key": "<you resource key>" } }}
When running in production, it's preferable to useenvironment variables:
SEARCH__CREDENTIAL__KEY="..."
Or use other secure ways of storing secrets likeAzure Key Vault.
For more details about Dependency Injection in ASP.NET Core apps, seeDependency injection with the Azure SDK for .NET.
An Azure AI Search service contains one or more indexes that providepersistent storage of searchable data in the form of JSON documents.(Ifyou're brand new to search, you can make a very rough analogy betweenindexes and database tables.) The Azure.Search.Documents client libraryexposes operations on these resources through three main client types.
SearchClient
helps with:
SearchIndexClient
allows you to:
SearchIndexerClient
allows you to:
Azure AI Search provides two powerful features:
Semantic ranking enhances the quality of search results for text-based queries. By enabling semantic ranking on your search service, you can improve the relevance of search results in two ways:
To learn more about Semantic Search, you can refer to thesample.
Additionally, for more comprehensive information about Semantic Search, including its concepts and usage, you can refer to thedocumentation. The documentation provides in-depth explanations and guidance on leveraging the power of Semantic Search in Azure Cognitive Search.
Vector search is an information retrieval technique that uses numeric representations of searchable documents and query strings. By searching for numeric representations of content that are most similar to the numeric query, vector search can find relevant matches, even if the exact terms of the query are not present in the index. Moreover, vector search can be applied to various types of content, including images and videos and translated text, not just same-language text.
To learn how to index vector fields and perform vector search, you can refer to thesample. This sample provides detailed guidance on indexing vector fields and demonstrates how to perform vector search.
Additionally, for more comprehensive information about vector search, including its concepts and usage, you can refer to thedocumentation. The documentation provides in-depth explanations and guidance on leveraging the power of vector search in Azure AI Search.
TheAzure.Search.Documents
client library (v11) provides APIs for data plane operations. ThepreviousMicrosoft.Azure.Search
client library (v10) is now retired. It has many similar looking APIs, so please be careful to avoid confusion whenexploring online resources. A good rule of thumb is to check for the namespaceusing Azure.Search.Documents;
when you're looking for API reference.
We guarantee that all client instance methods are thread-safe and independent of each other (guideline). This ensures that the recommendation of reusing client instances is always safe, even across threads.
Client options |Accessing the response |Long-running operations |Handling failures |Diagnostics |Mocking |Client lifetime
The following examples all use a simpleHotel data setthat you canimport into your own index from the Azure portal.These are just a few of the basics - pleasecheck out our Samples formuch more.
Let's start by importing our namespaces.
using Azure.Search.Documents;using Azure.Search.Documents.Indexes;using Azure.Core.GeoJson;
We'll then create aSearchClient
to access our hotels search index.
// Get the service endpoint and API key from the environmentUri endpoint = new Uri(Environment.GetEnvironmentVariable("SEARCH_ENDPOINT"));string key = Environment.GetEnvironmentVariable("SEARCH_API_KEY");string indexName = "hotels";// Create a clientAzureKeyCredential credential = new AzureKeyCredential(key);SearchClient client = new SearchClient(endpoint, indexName, credential);
There are two ways to interact with the data returned from a search query.Let's explore them with a search for a "luxury" hotel.
We can decorate our own C# types withattributes fromSystem.Text.Json
:
public class Hotel{ [JsonPropertyName("HotelId")] [SimpleField(IsKey = true, IsFilterable = true, IsSortable = true)] public string Id { get; set; } [JsonPropertyName("HotelName")] [SearchableField(IsFilterable = true, IsSortable = true)] public string Name { get; set; } [SimpleField(IsFilterable = true, IsSortable = true)] public GeoPoint GeoLocation { get; set; } // Complex fields are included automatically in an index if not ignored. public HotelAddress Address { get; set; }}public class HotelAddress{ public string StreetAddress { get; set; } [SimpleField(IsFilterable = true, IsSortable = true, IsFacetable = true)] public string City { get; set; } [SimpleField(IsFilterable = true, IsSortable = true, IsFacetable = true)] public string StateProvince { get; set; } [SimpleField(IsFilterable = true, IsSortable = true, IsFacetable = true)] public string Country { get; set; } [SimpleField(IsFilterable = true, IsSortable = true, IsFacetable = true)] public string PostalCode { get; set; }}
Then we use them as the type parameter when querying to return strongly-typed search results:
SearchResults<Hotel> response = client.Search<Hotel>("luxury");foreach (SearchResult<Hotel> result in response.GetResults()){ Hotel doc = result.Document; Console.WriteLine($"{doc.Id}: {doc.Name}");}
If you're working with a search index and know the schema, creating C# typesis recommended.
SearchDocument
like a dictionary for search resultsIf you don't have your own type for search results,SearchDocument
can beused instead. Here we perform the search, enumerate over the results, andextract data usingSearchDocument
's dictionary indexer.
SearchResults<SearchDocument> response = client.Search<SearchDocument>("luxury");foreach (SearchResult<SearchDocument> result in response.GetResults()){ SearchDocument doc = result.Document; string id = (string)doc["HotelId"]; string name = (string)doc["HotelName"]; Console.WriteLine($"{id}: {name}");}
TheSearchOptions
provide powerful control over the behavior of our queries.Let's search for the top 5 luxury hotels with a good rating.
int stars = 4;SearchOptions options = new SearchOptions{ // Filter to only Rating greater than or equal our preference Filter = SearchFilter.Create($"Rating ge {stars}"), Size = 5, // Take only 5 results OrderBy = { "Rating desc" } // Sort by Rating from high to low};SearchResults<Hotel> response = client.Search<Hotel>("luxury", options);// ...
You can use theSearchIndexClient
to create a search index. Fields can bedefined from a model class usingFieldBuilder
. Indexes can also definesuggesters, lexical analyzers, and more.
Using theHotel
sample above,which defines both simple and complex fields:
Uri endpoint = new Uri(Environment.GetEnvironmentVariable("SEARCH_ENDPOINT"));string key = Environment.GetEnvironmentVariable("SEARCH_API_KEY");// Create a service clientAzureKeyCredential credential = new AzureKeyCredential(key);SearchIndexClient client = new SearchIndexClient(endpoint, credential);// Create the index using FieldBuilder.SearchIndex index = new SearchIndex("hotels"){ Fields = new FieldBuilder().Build(typeof(Hotel)), Suggesters = { // Suggest query terms from the HotelName field. new SearchSuggester("sg", "HotelName") }};client.CreateIndex(index);
In scenarios when the model is not known or cannot be modified, you canalso create fields explicitly using convenientSimpleField
,SearchableField
, orComplexField
classes:
// Create the index using field definitions.SearchIndex index = new SearchIndex("hotels"){ Fields = { new SimpleField("HotelId", SearchFieldDataType.String) { IsKey = true, IsFilterable = true, IsSortable = true }, new SearchableField("HotelName") { IsFilterable = true, IsSortable = true }, new SearchableField("Description") { AnalyzerName = LexicalAnalyzerName.EnLucene }, new SearchableField("Tags", collection: true) { IsFilterable = true, IsFacetable = true }, new ComplexField("Address") { Fields = { new SearchableField("StreetAddress"), new SearchableField("City") { IsFilterable = true, IsSortable = true, IsFacetable = true }, new SearchableField("StateProvince") { IsFilterable = true, IsSortable = true, IsFacetable = true }, new SearchableField("Country") { IsFilterable = true, IsSortable = true, IsFacetable = true }, new SearchableField("PostalCode") { IsFilterable = true, IsSortable = true, IsFacetable = true } } } }, Suggesters = { // Suggest query terms from the hotelName field. new SearchSuggester("sg", "HotelName") }};client.CreateIndex(index);
You canUpload
,Merge
,MergeOrUpload
, andDelete
multiple documents froman index in a single batched request. There area few special rules for mergingto be aware of.
IndexDocumentsBatch<Hotel> batch = IndexDocumentsBatch.Create( IndexDocumentsAction.Upload(new Hotel { Id = "783", Name = "Upload Inn" }), IndexDocumentsAction.Merge(new Hotel { Id = "12", Name = "Renovated Ranch" }));IndexDocumentsOptions options = new IndexDocumentsOptions { ThrowOnAnyError = true };client.IndexDocuments(batch, options);
The request will succeed even if any of the individual actions fail andreturn anIndexDocumentsResult
for inspection. There's also aThrowOnAnyError
option if you only care about success or failure of the whole batch.
In addition to querying for documents using keywords and optional filters,you can retrieve a specific document from your index if you already know thekey. You could get the key from a query, for example, and want to show moreinformation about it or navigate your customer to that document.
Hotel doc = client.GetDocument<Hotel>("1");Console.WriteLine($"{doc.Id}: {doc.Name}");
All of the examples so far have been using synchronous APIs, but we provide fullsupport for async APIs as well. You'll generally just add anAsync
suffix tothe name of the method andawait
it.
SearchResults<Hotel> searchResponse = await client.SearchAsync<Hotel>("luxury");await foreach (SearchResult<Hotel> result in searchResponse.GetResultsAsync()){ Hotel doc = result.Document; Console.WriteLine($"{doc.Id}: {doc.Name}");}
To authenticate in aNational Cloud, you will need to make the following additions to your client configuration:
AuthorityHost
in the credential options or via theAZURE_AUTHORITY_HOST
environment variableAudience
inSearchClientOptions
// Create a SearchClient that will authenticate through AAD in the China national cloudstring indexName = "nycjobs";Uri endpoint = new Uri(Environment.GetEnvironmentVariable("SEARCH_ENDPOINT"));SearchClient client = new SearchClient(endpoint, indexName, new DefaultAzureCredential( new DefaultAzureCredentialOptions() { AuthorityHost = AzureAuthorityHosts.AzureChina }), new SearchClientOptions() { Audience = SearchAudience.AzureChina });
Any Azure.Search.Documents operation that fails will throw aRequestFailedException
withhelpfulStatus
codes. Many of these errors are recoverable.
try{ return client.GetDocument<Hotel>("12345");}catch (RequestFailedException ex) when (ex.Status == 404){ Console.WriteLine("We couldn't find the hotel you are looking for!"); Console.WriteLine("Please try selecting another."); return null;}
You can also easilyenable console logging if you want to digdeeper into the requests you're making against the service.
See ourtroubleshooting guide for details on how to diagnose various failure scenarios.
See ourSearch CONTRIBUTING.md for details on building,testing, and contributing to this library.
This project welcomes contributions and suggestions. Most contributions requireyou to agree to a Contributor License Agreement (CLA) declaring that you havethe right to, and actually do, grant us the rights to use your contribution. Fordetails, visitcla.microsoft.com.
This project has adopted theMicrosoft Open Source Code of Conduct.For more information see theCode of Conduct FAQor contactopencode@microsoft.com with anyadditional questions or comments.
Was this page helpful?
Was this page helpful?