Create Azure Search Index, Load Data And Query From .NET SDK

In this article, we will learn how to create Azure search index, load document/data to it and query the search results.

This is part 3 of a 3 article series about Azure search on the below topics
If you are interested in watching video on the same topic, please find it here. This article is in continuation from previous articles at this link.
 
In this article, we will learn how to create Azure search index, load document/data to it and query the search results. Before going into a step by step tutorial, let us understand what Azure search is from official Azure Search documentation:
 
Azure Search is a search-as-a-service cloud solution that gives developers APIs and tools for adding a rich search experience over private, heterogeneous content in web, mobile, and enterprise applications. Your custom code invokes data ingestion (indexing) to create and load an index. On the other side, your application code issues query requests and handles responses. The search experience is defined in your client using functionality from Azure Search, with query execution over a persisted index that you create, own, and store on Azure Search. 
 
Use Case
  • Suppose your source applications holding data will expose it in XML format (say in ftp or any path)
  • We will create console application utility which will run on scheduled time and read xml and load data to Azure Search Index.
  • It will also create Index (this can be done from Azure portal UI as well) and delete Index if already created (this is only for demo purposes, in a real business case deleting index everytime is not recommended)
  • Once index is created, data is loaded, we will use some sample queries to get search results
Pre-requisities
  • Azure Search Service is running (Refer to this link to create one), you can use a free service for this quickstart. // CHANGE THIS TO MY ARTICE LINK,
  • Azure search service admin key (Refer to this link on how to get one)
  • Visual Studio with Internet connection(to download NuGet packages)
Step 1
 
Create a console application (I have used C#)
 
Step 2 - Install NuGet packages
 
Go to Tools-> NuGet Package Manager-> Package manager console. Run the below command.
 
Note
We are using a package at this link
  1. Install-Package Microsoft.Azure.Search  
Troubleshoot- If you get the below error while installing, follow the steps mentioned below the error.
 
Install-Package - Failed to add reference to 'System.Runtime'. Please make sure that it is in the Global Assembly Cache.
  • Close Visual studio
  • Go to project folder and open .csproj file in notepad.
  • Add below entry in <ItemGroup> references. You will find other references as well here.
  • <Reference Include="System.Runtime" />
  • Save file and close it from notepad
  • Open project again in visual studio
  • Try command again ‘Install-Package Microsoft.Azure.Search’
If everything goes well, you should see the below message,
 
Create Azure Search Index, Load Data And Query From .NET SDK
 
Step 3 
 
Add below dll references to project.
  1. System.ComponentModel.DataAnnotations.dll  
Add reference to below dll if not already added (in my case, it added automatically for first time but was missing the second time).
 
Project Path\AzureSearchConsole\packages\Microsoft.Rest.ClientRuntime.Azure.3.3.19\lib\net452\Microsoft.Rest.ClientRuntime.Azure.dll
 
Step 4 - Create sample source xml
 
Create s sample xml file and save it in in some physical folder,
  1. <?xml version="1.0" encoding="UTF-8" standalone="yes"?>    
  2. <root>    
  3.     <Persons>    
  4.         <Person>    
  5.             <ID>1</ID>    
  6.             <NAME>Bruce Wayne</NAME>    
  7.             <ScreenName>Batman</ScreenName>    
  8.             <Power>strength, stamina, endurance, intellect</Power>    
  9.         </Person>    
  10.         <Person>    
  11.             <ID>2</ID>    
  12.             <NAME>Clark Kent</NAME>    
  13.             <ScreenName>Superman</ScreenName>    
  14.             <Power>can fly, freeze breath, durablity</Power>    
  15.         </Person>    
  16.         <Person>    
  17.             <ID>3</ID>    
  18.             <NAME>Barry Allen</NAME>    
  19.             <ScreenName>Flash</ScreenName>    
  20.             <Power>fastest man, durablity, metahuman</Power>    
  21.         </Person>    
  22.         <Person>    
  23.             <ID>4</ID>    
  24.             <NAME>Princess Diana</NAME>    
  25.             <ScreenName>Wonder woman</ScreenName>    
  26.             <Power>athlete, acrobat, fighter and strategist</Power>    
  27.         </Person>    
  28.     </Persons>    
  29. </root>     
Step 5
 
Create a entity class Person (to hold above xml data).
  1. using Microsoft.Azure.Search;  
  2. // other default references here  
  3. namespace AzureSearchConsole    
  4. {    
  5.     class Person    
  6.     {    
  7.         [System.ComponentModel.DataAnnotations.Key]    
  8.         [IsFilterable]    
  9.         public string ID { getset; }    
  10.     
  11.         [IsSearchable, IsFilterable, IsSortable, IsFacetable]    
  12.         public string NAME { getset; }    
  13.     
  14.         [IsSearchable, IsFilterable, IsSortable, IsFacetable]    
  15.         public string ScreenName { getset; }    
  16.     
  17.         [IsSearchable, IsFilterable, IsSortable, IsFacetable]    
  18.         public string Power { getset; }    
  19.     }    
  20. }     
Step 6
 
Replace main method in program.cs with below,
  1. static void Main(string[] args)  
  2.       {  
  3.               string searchServiceName = "azsearchdemofree";  
  4.               string queryApiKey = "MYADMINAPIKEYFROMAZUREPORTAL";  // Replace this with actual key
  5.               string indexName = "superheroes";  
  6.               SearchServiceClient serviceClient = CreateSearchServiceClient(searchServiceName, queryApiKey);  
  7.               Console.WriteLine("{0}""Deleting index...\n");  
  8.               DeleteIndexIfExists(indexName, serviceClient);  
  9.               Console.WriteLine("{0}""Creating index...\n");  
  10.               CreateIndex(indexName, serviceClient);  
  11.               ISearchIndexClient indexClient = serviceClient.Indexes.GetClient(indexName);  
  12.               Console.WriteLine("{0}""Uploading documents...\n");  
  13.               UploadDocuments(indexClient);  
  14.               ISearchIndexClient indexClientForQueries = CreateSearchIndexClient(indexName, searchServiceName, queryApiKey);  
  15.               RunQueries(indexClientForQueries);  
  16.               Console.WriteLine("{0}""Complete.  Press any key to end application...\n");  
  17.               Console.ReadKey();  
  18.       }  
Step 7 - Add supporting methods called in above main method
 
Below methods are to create index and search client, using this two object type we will get a different method available in Search SDK to performs operations on Azure Search.
  1. private static SearchIndexClient CreateSearchIndexClient(string indexName, string searchServiceName, string queryApiKey)  
  2. {  
  3.            SearchIndexClient indexClient = new SearchIndexClient(searchServiceName, indexName, new SearchCredentials(queryApiKey));  
  4.            return indexClient;  
  5. }  
  6. private static SearchServiceClient CreateSearchServiceClient(string searchServiceName, string adminApiKey)  
  7. {  
  8.            SearchCredentials creds = new SearchCredentials(adminApiKey);  
  9.            SearchServiceClient serviceClient = new SearchServiceClient(searchServiceName, creds);  
  10.            return serviceClient;  
  11. }  
  1. // Delete an existing index to reuse its name  
  2. private static void DeleteIndexIfExists(string indexName, SearchServiceClient serviceClient)  
  3. {  
  4.            if (serviceClient.Indexes.Exists(indexName))  
  5.            {  
  6.                serviceClient.Indexes.Delete(indexName);  
  7.            }  
  8. }  
Below method will create index and create field based on Person class we defined
  1. // Create an index whose fields correspond to the properties of the Person class.  
  2. // The fields of the index are defined by calling the FieldBuilder.BuildForType() method.  
  3. private static void CreateIndex(string indexName, SearchServiceClient serviceClient)  
  4. {  
  5.            var definition = new Index()  
  6.            {  
  7.                Name = indexName,  
  8.                Fields = FieldBuilder.BuildForType<Person>()  
  9.            };  
  10.            serviceClient.Indexes.Create(definition);  
  11. }  
Next method is to load document(records) in Azure Search Index (database/table). We would be parsing our source XML data to get actual person data and add it to IndexClient in batch. And finally call Index method by passing batch object to actually index our data.
  1. // Upload documents as a batch  
  2.        private static void UploadDocuments(ISearchIndexClient indexClient)  
  3.        {  
  4.            XmlDocument xmlDoc = new XmlDocument();  
  5.            xmlDoc.Load(@"F:\Sid\AzureSearchConsole\AzureSearchConsole\sourcedata.xml");  
  6.            XmlNodeList nodeList = xmlDoc.DocumentElement.SelectNodes("/root/Persons/Person");  
  7.            List<Person> personCollections = new List<Person>();  
  8.            var actions = new IndexAction<Person>[4];  
  9.            int i = 0;  
  10.            foreach (XmlNode node in nodeList)  
  11.            {  
  12.                Person person = new Person();  
  13.                person.ID = node.SelectSingleNode("ID").InnerText;  
  14.                person.NAME = node.SelectSingleNode("NAME").InnerText;  
  15.                person.ScreenName = node.SelectSingleNode("ScreenName").InnerText;  
  16.                person.Power = node.SelectSingleNode("Power").InnerText;  
  17.                personCollections.Add(person);  
  18.                actions[i] = IndexAction.Upload(person);  
  19.                i++;  
  20.            }  
  21.            var batch = IndexBatch.New(actions);  
  22.            try  
  23.            {  
  24.                indexClient.Documents.Index(batch);  
  25.            }  
  26.            catch (Exception e)  
  27.            {  
  28.                // When a service is under load, indexing might fail for some documents in the batch.   
  29.                // Depending on your application, you can compensate by delaying and retrying.   
  30.                // For this simple demo, we just log the failed document keys and continue.  
  31.                Console.WriteLine("Failed to index some of the documents: {0}",  
  32.                    String.Join(", ", e.Message));  
  33.            }  
  34.            // Wait 2 seconds before starting queries  
  35.            Console.WriteLine("Waiting for indexing...\n");  
  36.            Thread.Sleep(2000);  
  37.        }  
Next add method which will run queries.
  1. // Add query logic and handle results  
  2.         private static void RunQueries(ISearchIndexClient indexClient)  
  3.         {  
  4.             SearchParameters parameters;  
  5.             DocumentSearchResult<Person> results;  
  6.   
  7.             // Query 1   
  8.             Console.WriteLine("Query 1: Search for term 'batman', returning the full document");  
  9.             parameters = new SearchParameters();  
  10.             results = indexClient.Documents.Search<Person>("batman", parameters);  
  11.             WriteDocuments(results);  
  12.   
  13.             // Query 2  
  14.             Console.WriteLine("Query 2: Search on the term 'fly', returning selected fields");  
  15.             Console.WriteLine("Returning only these fields: NAME, ScreenName, Power:\n");  
  16.             parameters =  
  17.                 new SearchParameters()  
  18.                 {  
  19.                     Select = new[] { "NAME""ScreenName","Power" },  
  20.                 };  
  21.             results = indexClient.Documents.Search<Person>("fly", parameters);  
  22.             WriteDocuments(results);  
  23.   
  24.             // Query 3  
  25.             Console.WriteLine("Query 3: Search for the terms 'acrobat' and 'metahuman'");  
  26.             Console.WriteLine("Returning only these fields: NAME, ScreenName, Power:\n");  
  27.             parameters =  
  28.                 new SearchParameters()  
  29.                 {  
  30.                     Select = new[] { "NAME""ScreenName""Power" },  
  31.                 };  
  32.             results = indexClient.Documents.Search<Person>("acrobat, metahuman", parameters);  
  33.             WriteDocuments(results);  
  34.   
  35.               
  36.         }  
Next add method which will display search results
  1. // Handle search results, writing output to the console  
  2.        private static void WriteDocuments(DocumentSearchResult<Person> searchResults)  
  3.        {  
  4.            foreach (SearchResult<Person> result in searchResults.Results)  
  5.            {  
  6.                Console.WriteLine("ID:--" + result.Document.ID);  
  7.                Console.WriteLine("Name:--" + result.Document.NAME);  
  8.                Console.WriteLine("ScreenName:--" + result.Document.ScreenName);  
  9.                Console.WriteLine("Power:--" + result.Document.Power);  
  10.            }  
  11.            Console.WriteLine();  
  12.        }  
Step 7
 
Run the console application, we should see the below output in console.
 
Create Azure Search Index, Load Data And Query From .NET SDK
Notes on output
  • Id column is empty for query 2 and 3, this is because in this query we have specified to return specific fields and ID is not mentioned.
  • For multiple terms specified like acrobat and metahuman, we got 2 results which is Flash and Wonder woman which are powers assigned to individuals.
  • We can also specify search query based on specific column like Screen name = 'Wonder woman' etc.
Now let us go to Azure portal to see indexes created and data which is being loaded by our console application. 
 
Select Azure Search Service,
 
In overview tab, click on Indexes as marked in below screenshot.
 
We can see 4 as document count
 
Create Azure Search Index, Load Data And Query From .NET SDK
 
Click on superheroes, we will get the below screen, without entering any query just click on Search
 
Create Azure Search Index, Load Data And Query From .NET SDK
 
This concludes our article on how to create console utility application which can load data to Azure Search index. This would be a real use case because, mostly in business cases, data would be exposed by multiple external applications or datasources and can be used to display search results in  enterprise search portal.
 
You can download a sample attached with this article or clone it from this github repo.
 
Hope you enjoyed reading..!!