Joydip Kanjilal
Contributor

How to use Azure Search in .Net

how-to
Apr 23, 20185 mins
Cloud ComputingDevelopment ToolsMicrosoft .NET

Take advantage of the Azure Search service to build powerful search capabilities into your web and mobile applications

cloud trends 2017
Credit: Thinkstock

Azure Search is a powerful search service available in Microsoft’s Azure cloud. Azure Search provides excellent support for indexing and querying data while at the same time shielding you from the intricacies of deployment, management, and search algorithms.

Azure Search gives you an easy way to integrate powerful search capabilities (scalable full-text search, indexing, filtering, geospatial search, etc.) into your web and mobile applications. In this article we’ll look at how we can work with the Azure Search SDK in .Net.

How to work with the Azure Search SDK

Our journey will take us through the following steps.

  1. Create a new Azure Search service via the Azure Portal if you don’t have one
  2. Create a .Net application to work with Azure Search
  3. Create and initialize a SearchServiceClient
  4. Create an index
  5. Upload documents to the index
  6. Query the Azure Search service

The Azure Search SDK comprises the Microsoft.Azure.Search client library. You can use the Azure Search SDK to upload your documents and execute queries without having to deal with the JSON data. The Microsoft.Azure.Search library contains the Index, Field, and Document classes, and it supports operations such as Indexes.Create (to create an Azure Search index) and Documents.Search (to search for documents in an Azure Search index) on the SearchServiceClient and the SearchIndexClient classes respectively so as to enable you to create and manage indexes and documents in the Azure Cloud.

Create an Azure Search service

Creating an Azure Search service is quite straightforward. Naturally you will need an Azure account. You can create one for free if you don’t have one. Follow this link to create a free Azure account.

Sign in to the Azure portal and create a new Azure Search service (assuming you don’t already have one to use). You can follow the steps outlined here to provision the service.

Create a .Net console application

Create a new Console Application Project in Visual Studio and save it with a name. Select the project in the Solution Explorer window and install the Microsoft.Azure.Search package via the NuGet Package Manager. Once the installation is successful, you are all set to begin working with the Azure Search SDK.

Let’s roll our sleeves now and write some code. Create the following POCO class in the Console Application project you just created. We will use it to represent the search document for now. We will upload and search some real documents later in this article.

public class Author
    {
        public string Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Address { get; set; }
    }

Create a SearchServiceClient and connect to an Azure Search service

The following code snippet can be used to create a SearchServiceClient instance and connect to the Azure Search service using the service name and the API key.

static string serviceName ="IDGSearch";
static string apiKey ="Enter your Api key here";
SearchServiceClient serviceClient = new SearchServiceClient(serviceName, new SearchCredentials(apiKey));

Create an index in an Azure Search service

When working with Azure Search you should create one or more indexes. An index may be defined as a persistent store of documents and can be created using a REST API or the .Net SDK. The following code snippet illustrates how you can create a new index. Note that this method accepts a reference to the SearchServiceClient and the name of the index to be created as parameters.

private static void CreateIndex(SearchServiceClient client, string indexName)
{
      var indexDefinition = new Index()
      {
          Name = indexName,
          Fields = new[]
          {
            new Field(“Id”, DataType.String) { IsKey = true},
            new Field(“FirstName”, DataType.String) { IsSearchable = true, IsSortable = true, IsFilterable = true},
            new Field(“LastName”, DataType.String) { IsSearchable = true, IsSortable = true, IsFilterable = true},
            new Field(“Address”, DataType.String) { IsSearchable = true, IsSortable = true},
          }
       };
     client.Indexes.Create(indexDefinition);
}

Delete an index from an Azure Search service

You can also delete an index if it is no longer needed. The following code snippet illustrates how to delete an index (if it exists).

private static void DeleteIndex(SearchServiceClient serviceClient, string indexName)
{
    if (serviceClient.Indexes.Exists(indexName))
    {
       serviceClient.Indexes.Delete(indexName);
    }
}

Upload documents to an Azure Search index

There are a couple of ways to populate Azure Search index with data, using either the .Net SDK or the Azure Search REST API. The Upload method given below shows how you can take advantage of the Azure Search Client SDK to upload one or more documents into an Index in a batch.

private static void Upload(ISearchIndexClient indexClient, List<Author> authors)
        {
            var indexBatch = IndexBatch.Upload(authors);
            indexClient.Documents.Index(indexBatch);
        }

Assuming that you have already created and uploaded documents, you can take advantage of the Search method to locate documents in the Azure Search index. The following code illustrates how this can be achieved.

private static void Search(ISearchIndexClient indexClient)
        {
            SearchParameters parameters = new SearchParameters()
                {
                    Select = new[] { “FirstName”, “LastName” }
                };
            DocumentSearchResult<Author> searchResults = indexClient.Documents.Search<Author>(“Joydip”, parameters);
            foreach (SearchResult<Author> result in searchResults.Results)
            {
                var document = result.Document;
                Console.WriteLine(document.FirstName + “t” + document.LastName);
            }
        }

Azure Search is a full-featured search engine that provides a simple query syntax and also supports Lucene syntax for more advanced uses like fuzzy matching and regular expressions. It can automatically index Azure data sources including Azure SQL Database, Azure Cosmos DB, and Azure Blob storage, and can be used to index and search data from any source that can be uploaded in JSON.

Joydip Kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author