Azure Search, The basics

Written by Henk Boelman on 27 December 2016

Adding search to a website is always a bit tricky and takes a lot of time to implement correctly. Azure Search and the Azure Search Library makes adding search capability to a website or application a lot easier. Azure Search runs as a service in the Azure Cloud so their is no need anymore to setup and maintain expensive virtual machines. And even better the first 10.000 documents in the search DB are free.

A complete code sample on can be found on GitHub.

Step 1 - Create a Azure Search Service

In the azure portal you can create a new Azure Search Service

Step 2 - Creating the index in code

Add the nuget package for Azure Search to your Visual Studio project. To connect from your solution to Azure search you need 2 text strings to authenticate. These values can be found in the Azure portal by clicking on the Azure Search Service blade.

1  - SearchServiceName (The name you entered in the URL field while setting up the service)
2 - SearchServiceApiKey (This can be found under settings and Keys)

To connect to your search service you can use the following code:

SearchServiceClient searchClient = new SearchServiceClient(searchServiceName, new SearchCredentials(searchServiceApiKey));

Creating a Index can be done in code or in the Azure portal. First create a class that contains the model you want to store. The fields specify the properties in the Index.

[SerializePropertyNamesAsCamelCase]
public class Trip
{
    [Key, IsFilterable]
    public string Id { get; set; }
 
    [IsSearchable, IsFilterable, IsSortable]
    public string Name { get; set; }
 
    [IsFilterable, IsSortable, IsFacetable]
    public int? Duration { get; set; }
 
    [IsSearchable, IsFilterable, IsFacetable]
    public string[] Tags { get; set; }
}

The fields can be of the types below and can be decorated with the list of properties. Decorating a field with IsKey is mandatory.

FieldDataTypes Field properties
String Name
StringCollection Type
Boolean IsSearchable
Int32 IsFilterable
Double IsSortable
DateTimeOffset IsFacetable
GeographyPoint IsShownInSuggestions
GeographyPolygon IsKey
IsRetrievable

If your model is done, you are ready to create the Index. This can be done with the following code:

SearchServiceClient searchClient = new SearchServiceClient(searchServiceName, new SearchCredentials(searchServiceApiKey));
var definition = new Index()
{
   Name = indexName,
   Fields = FieldBuilder.BuildForType<Trip>()
};
searchClient.Indexes.Create(definition);

After running the code, you can have a look in the portal at the created Index.

Step 3 - Adding / updating data

Adding data to a Index is straightforward. Create a list of objects you want to add or update and add them in a batch to the Index. (it will update your document if the Key is already in the index).

SearchServiceClient searchClient = new SearchServiceClient(searchServiceName, new SearchCredentials(searchServiceApiKey));
ISearchIndexClient indexClient = _searchClient.Indexes.GetClient(indexName);
List<Trip> documents = new List<Trip>()
{
    new Trip()
    {
        Id = Guid.NewGuid().ToString(),
        Name = "Trip to Alaska",
        Tags = new string[] {"Alaska", "Holiday"},
        Duration = 14
    },
    new Trip()
    {
        Id = Guid.NewGuid().ToString(),
        Name = "Cruise to Sweden",
        Tags = new string[] {"Sweden", "Cruise"},
        Duration = 14
    }
};
IndexBatch<Trip> batch = IndexBatch.Upload(documents);
indexClient.Documents.Index(batch);

When the documents are added to the Index you can view the documents in your index through the search explorer in the Azure Portal. 

Step 4 - Searching in the Index

Now that there are documents in the Index, you can search them. The most basic search method is to search the entire index for a specific term.

SearchServiceClient searchClient = new SearchServiceClient(searchServiceName, new SearchCredentials(searchServiceApiKey));
ISearchIndexClient indexClient = _searchClient.Indexes.GetClient(indexName);
var results = indexClient.Documents.Search<Trip>("sweden");

To make the result more narrow you can use the SearchParameters object. The code below returns all trips with a duration less then 18 days with a maximum of 2 results an ordered by duration. The result object only contains the value for name and duration.

var parameters = new SearchParameters()
{
   Filter = "duration lt 18",
   Top = 2,
   OrderBy = new[] { "duration desc" },
   Select = new[] { "name", "duration" }
};
SearchServiceClient searchClient = new SearchServiceClient(searchServiceName, new SearchCredentials(searchServiceApiKey));
ISearchIndexClient indexClient = _searchClient.Indexes.GetClient(indexName);
var results = indexClient.Documents.Search<Trip>("*",parameters );

Want to know more, check out the Microsoft documentation for more about search queries and faceting.

With these small code samples above you should be able to create a Azure Search Service, add a Index and add or update documents in it. Please have a look at the code sample at GitHub.

Handy links:

If you have comments or questions. Drop me a email or leave a comment below.


Leave a comment