Azure Cognitive Search from .NET Core and C#

The Azure Cognitive Search engine is the search of choice in the Microsoft Azure. The search engine can be used in a myriad of ways and there are so many options that it can be difficult to find a starting point.

To help myself, I made this simple class that implements one of the simplest setups and a great starting point for more advanced searches.

The class is an example on how to do a free text search in one index.

THE NUGET REFERENCES: 

The code references the following packages:

STEP 1: DEFINE A MODEL CLASS FOR THE INDEX

You must define a model class that matches the fields you wish to have returned from the index. This is my sample index called “advert”:

Sample Advert Index

And I have defined the fields relevant for my search result:

public class Advert
{
  public string Id { get; set; }
  public string Title { get; set; }
  public string Description { get; set; }
}

STEP 2: THE SAMPLE SEARCH CLASS:

This is just an example search class that implement the most basic functions. You need to specify your own URL to the search engine and the proper API key.

using Azure;
using Azure.Search.Documents;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace MyCode
{
  public class AzureSearch
  {
    public async Task<IEnumerable<string>> Search(string query)
    {
      SearchClient searchClient = CreateSearchClientForQueries("advert");
      SearchOptions options = new SearchOptions() { IncludeTotalCount = true };
      var results = await searchClient.SearchAsync<Advert>(query, options);

      List<string> documents = new List<string>();
      Console.WriteLine(results.Value.TotalCount);
      foreach (var s in results.Value.GetResults())
      {
        documents.Add(s.Document.Title);
      }
      return documents;
    }

    private static SearchClient CreateSearchClientForQueries(string indexName)
    {
      string searchServiceEndPoint = "https://mysearch.windows.net";
      string queryApiKey = "the api key";

      SearchClient searchClient = new SearchClient(new Uri(searchServiceEndPoint), indexName, new AzureKeyCredential(queryApiKey));
      return searchClient;
    }
  }
}

STEP 3: THE USAGE

Remember that the code above is just a sample on how to do a basic free-text search.

class Program
{
  static void Main(string[] args)
  {
    var result = new AzureSearch().Search("BrianCaos").Result;
    foreach (var r in result)
      Console.WriteLine(r);
  }
}

MORE ADVANCED SEARCHES:

To do more advanced searches, you usually modify the SearchOptions. For example, if you wish to apply a filter to the search, you can use the “Filter” property. This property takes a slightly different format, as “=” is written “eq”, “>” is “gt” and “<” is “lt”.

public async Task<IEnumerable<string>> Search(string query)
{
  SearchClient searchClient = CreateSearchClientForQueries("advert");
  SearchOptions options = new SearchOptions() 
  { 
    IncludeTotalCount = true, 
    Filter = "MyField eq true" 
  };
  var results = await searchClient.SearchAsync<Advert>(query, options);

  List<string> documents = new List<string>();
  Console.WriteLine(results.Value.TotalCount);
  foreach (var s in results.Value.GetResults())
  {
    documents.Add(s.Document.Title);
  }
  return documents;
}

PAGINATION:

To do pages searches, you use the SearchOptions again. Use the “Size” and “Skip” parameters to specify paging. “Size” determines the number of results, “Skip” determines how many results to skip before returning results. This example implements a 1-based paging:

public async Task<IEnumerable<string>> Search(string query, int page, int pageSize)
{
  SearchClient searchClient = CreateSearchClientForQueries("advert");
  SearchOptions options = new SearchOptions() 
  { 
    IncludeTotalCount = true, 
    Size = pageSize,
    Skip = (page-1)*pageSize
  };
  var results = await searchClient.SearchAsync<Advert>(query, options);

  List<string> documents = new List<string>();
  Console.WriteLine(results.Value.TotalCount);
  foreach (var s in results.Value.GetResults())
  {
    documents.Add(s.Document.Title);
  }
  return documents;
}

MORE TO READ:

About briancaos

Developer at Pentia A/S since 2003. Have developed Web Applications using Sitecore Since Sitecore 4.1.
This entry was posted in .NET Core, c#, General .NET, Microsoft Azure and tagged , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.