Step by step: .Net Core and Azure Search is small introduction on how to connect to Azure Search, create and delete indexes, models, add documents and perform basic queries.

Let’s go for it:

1. Create an Azure Search service#


Create an Azure Search service in your Azure subscription, and get the Azure Search name and primary Read-Write key.

Find the steps here.

2. Create a folder for your project#


Open a command prompt and run:

1mkdir netCoreAzureSearch

3. Create the project#

1cd netCoreAzureSearch
2dotnet new console

4. Add a reference to Microsoft.Azure.Search#


Microsoft.Azure.Search will allow your application to talk with Azure Search.

1dotnet add package  Microsoft.Azure.Search -v 3.0.4
2dotnet restore

5. Replace the content of Program.cs#


Replace the content of Program.cs with the following contents and be sure to replace the values in lines 13 and 16 with the Azure Search service name and key from step 1:

  1namespace netCoreAzureSearch
  2{
  3    using System;
  4    using Microsoft.Azure.Search;
  5    using System.Linq;
  6    using System.Collections.Generic;
  7    using Microsoft.Azure.Search.Models;
  8    
  9    class Program
 10    {
 11        static void Main(string[] args)
 12        {
 13            var azureSearchName = "[Your Azure Search Name]";
 14 
 15            // The key to you cosmosdb
 16            var azureSearchKey = "[Your Azure Search Key]";
 17
 18            // Index name variable
 19            string indexName = "books";
 20            
 21            // Create a service client connection
 22            ISearchServiceClient azureSearchService = new SearchServiceClient(azureSearchName, new SearchCredentials(azureSearchKey));
 23             
 24            // Get the Azure Search Index
 25            ISearchIndexClient indexClient = azureSearchService.Indexes.GetClient(indexName);
 26
 27            // If the Azure Search Index exists delete it.
 28            Console.WriteLine( "Deleting index...\n"); 
 29            if (azureSearchService.Indexes.Exists(indexName))
 30            {
 31                 azureSearchService.Indexes.Delete(indexName);
 32            }
 33
 34            // Create an Index Model
 35            Console.WriteLine( "Creating index Model...\n"); 
 36            Index indexModel = new Index()
 37            {
 38                Name = indexName,
 39                Fields = new[]
 40                {
 41                    new Field("ISBN", DataType.String) { IsKey = true, IsRetrievable = true, IsFacetable = false },
 42                    new Field("Titulo", DataType.String) {IsRetrievable = true, IsSearchable = true, IsFacetable = false },
 43                    new Field("Autores", DataType.Collection(DataType.String)) {IsSearchable = true, IsRetrievable = true, IsFilterable = true, IsFacetable = false },
 44                    new Field("FechaPublicacion", DataType.DateTimeOffset) { IsFilterable = true, IsRetrievable = false, IsSortable = true, IsFacetable = false },
 45                    new Field("Categoria", DataType.String) { IsFacetable = true, IsFilterable= true, IsRetrievable = true }
 46
 47                }                   
 48            };
 49            
 50            // Create the Index in AzureSearch
 51            Console.WriteLine( "Creating index...\n"); 
 52            var resultIndex = azureSearchService.Indexes.Create(indexModel);
 53
 54            // Add documents to the Index
 55            Console.WriteLine( "Add documents...\n");
 56            var listBooks = new BookModel().GetBooks();
 57            indexClient.Documents.Index(IndexBatch.MergeOrUpload<BookModel>(listBooks));
 58            System.Threading.Thread.Sleep(1000);
 59
 60            // Search by word
 61            Console.WriteLine("{0}", "Searching documents 'Cloud'...\n");
 62            Search(indexClient, searchText: "Cloud");
 63            System.Threading.Thread.Sleep(1000);
 64
 65            // Search everything and filter
 66            Console.WriteLine("\n{0}", "Filter documents by Autores 'Eugenio Betts'...\n");
 67            Search(indexClient, searchText: "*", filter: "Autores / any(t: t eq 'Eugenio Betts')");
 68            System.Threading.Thread.Sleep(1000);
 69
 70            // Search everything and order
 71            Console.WriteLine("\n{0}", "order by FechaPublicacion\n");
 72            Search(indexClient, searchText: "*", order: new List<string>() { "FechaPublicacion" });
 73            System.Threading.Thread.Sleep(1000);
 74
 75            //Search everything and facet
 76            Console.WriteLine("\n{0}", "Facet by Categoria \n");
 77            Search(indexClient, searchText: "*", facets: new List<string>() { "Categoria" });
 78            System.Threading.Thread.Sleep(1000);
 79        }
 80
 81         private static void Search(ISearchIndexClient indexClient, string searchText, string filter = null, List<string> order = null, List<string> facets = null)
 82        {
 83            // Execute search based on search text and optional filter
 84            var sp = new SearchParameters();
 85
 86            // Add Filter
 87            if (!String.IsNullOrEmpty(filter))
 88            {
 89                sp.Filter = filter;
 90            }
 91
 92            // Order
 93            if (order != null && order.Count > 0)
 94            {
 95                sp.OrderBy = order;
 96            }
 97
 98            // facets
 99            if (facets != null && facets.Count > 0)
100            {
101                sp.Facets = facets;
102            }
103
104            // Search
105            DocumentSearchResult<BookModel> response = indexClient.Documents.Search<BookModel>(searchText, sp);
106           
107            foreach (SearchResult<BookModel> result in response.Results)
108            {
109                Console.WriteLine(result.Document + " - Score: " + result.Score);
110            }
111
112            if (response.Facets != null)
113            {
114                foreach (var facet in response.Facets)
115                {
116                    Console.WriteLine("\n Facet Name: " + facet.Key);
117                    foreach (var value in facet.Value)
118                    {
119                        Console.WriteLine("Value :" + value.Value + " - Count: " + value.Count);
120                    }
121                }
122            }
123        }
124    }
125
126    /// <summary>
127    /// A simple class representing a book
128    /// </summary>
129    public  class BookModel
130    {
131        public string ISBN { get; set; }
132        public string Titulo { get; set; }
133        public List<string> Autores { get; set; }
134        public DateTimeOffset FechaPublicacion { get; set; }
135        public string Categoria { get; set; }
136
137        public List<BookModel> GetBooks()
138        {
139            var listBooks = new List<BookModel>();
140            listBooks.Add(new BookModel()
141            {
142                ISBN = "9781430224792",
143                Titulo = "Windows Azure Platform (Expert's Voice in .NET)",
144                Categoria = "Comic",
145                Autores = new List<string>() {"Redkar", "Tejasw" },
146                FechaPublicacion = DateTimeOffset.Now.AddDays(-2)
147            });
148
149            listBooks.Add(new BookModel()
150            {
151                ISBN = "9780470506387",
152                Titulo = "Cloud Computing with the Windows Azure Platform",
153                Categoria = "Terror",
154                Autores = new List<string>() { "Roger Jennings"},
155                FechaPublicacion = DateTimeOffset.Now
156            });
157
158            listBooks.Add(new BookModel()
159            {
160                ISBN = "9780889222861",
161                Titulo = "Azure Blues",
162                Categoria = "Terror",
163                Autores = new List<string>() { "Gilbert", "Gerry", "Rogery Landing"},                
164                FechaPublicacion = DateTimeOffset.Now.AddMonths(-3)
165            });
166
167            listBooks.Add(new BookModel()
168            {
169                ISBN = "9780735649675",
170                Titulo = "Moving Applications to the Cloud on the Microsoft Azure(TM) Platform",
171                Categoria = "Fiction",
172                Autores = new List<string>() { "Pace", "Eugenio Betts", "Dominic Densmore", "Scott; Dunn", "Ryan Narumoto", "Masashi Woloski", "Matias" },
173                FechaPublicacion = DateTimeOffset.Now
174            });
175
176            return listBooks;
177        }
178
179        public override string ToString()
180        {
181            return "ISBN: " + this.ISBN + " - titulo: " + this.Titulo + " - Autores: " + String.Join(", ", this.Autores);     
182        }
183    }
184}

6. Run the application#


Run the following commands:

1dotnet build
2dotnet run

You can get the code here.

See you soon!