Using Azure Cognitive Search Suggesters in ASP.NET Core and Autocomplete

This post shows how to implement an autocomplete in an ASP.NET Core Razor Page using Azure Cognitive Search Suggesters.


Posts in this series


2021-08-20 Updated packages and search

Create the index with the Suggester

To use Suggesters in Azure Cognitive Search, the index requires a suggester definition. This can be implemented using the Azure.Search.Documents Nuget package. A new SearchIndex can be created and the Suggesters list can be used to add a new suggester. The name of the suggester is required so that it can be used in the search and the fields of the search index which are to be used in the suggester. The suggester fields must exist in the index.

public async Task CreateIndex()
	FieldBuilder bulder = new FieldBuilder();
	var definition = new SearchIndex(_index, bulder.Build(typeof(PersonCity)));
	definition.Suggesters.Add(new SearchSuggester(
		"personSg", new string[] { "Name", "FamilyName", "Info", "CityCountry" }

	await _searchIndexClient.CreateIndexAsync(definition).ConfigureAwait(false);

Searching the index using the Suggester

The SearchClient is used to send the search requests to Azure Cognitive Search. The Suggest method prepares the SuggestOptions options and uses the Azure.Search.Documents SuggestAsync method of the SearchClient instance to query the index.

public class SearchProviderAutoComplete
	private readonly SearchClient _searchClient;
	private readonly string _index;

	public SearchProviderAutoComplete(IConfiguration configuration)
		_index = configuration["PersonCitiesIndexName"];

		Uri serviceEndpoint = new Uri(configuration["PersonCitiesSearchUri"]);
		AzureKeyCredential credential = new AzureKeyCredential(configuration["PersonCitiesSearchApiKey"]);
		_searchClient = new SearchClient(serviceEndpoint, _index, credential);


	public async Task<SuggestResults<PersonCity>> Suggest(
		bool highlights, bool fuzzy, string term)
		SuggestOptions sp = new SuggestOptions()
			UseFuzzyMatching = fuzzy, 
			Size = 5,

		if (highlights)
			sp.HighlightPreTag = "<b>";
			sp.HighlightPostTag = "</b>";

		var suggestResults = await _searchClient.SuggestAsync<PersonCity>(term, "personSg", sp).ConfigureAwait(false);
		return suggestResults.Value;

	//public async Task<List<string>> AutoComplete(string term)
	//    AutocompleteOptions ap = new AutocompleteOptions()
	//    {
	//        UseFuzzyMatching = false, Size = 5, 
	//    };

	//    var autocompleteResult = await _searchClient.AutocompleteAsync(term, "personSg", ap).ConfigureAwait(false);

	//    List<string> autocomplete = autocompleteResult.Value.Results.Select(x => x.Text).ToList();
	//    return autocomplete;

Autocomplete in ASP.NET Razor Page

The OnGetAutoCompleteSuggest method of the Razor Page sends a suggest search request using no highlighting and a fuzzy search with the required term. If you were using an Azure Cognitive Search AuthComplete together with the suggester, then maybe the fuzzy could be set to false.

public class SearchAutoCompleteModel : PageModel
	private readonly SearchProviderAutoComplete _searchProviderAutoComplete;
	private readonly ILogger<IndexModel> _logger;

	public string SearchText { get; set; }

	public SuggestResults<PersonCity> PersonCities;

	public SearchAutoCompleteModel(SearchProviderAutoComplete searchProviderAutoComplete,
		ILogger<IndexModel> logger)
		_searchProviderAutoComplete = searchProviderAutoComplete;
		_logger = logger;

	public void OnGet()

	public async Task<ActionResult> OnGetAutoCompleteSuggest(string term)
		//List<string> suggestions = PersonCities.Results.Select(x => x.Text).ToList();
		PersonCities = await _searchProviderAutoComplete.Suggest(false, true, term);
		SearchText = term;

		return new JsonResult(PersonCities.Results);

	//public async Task OnGetAutoComplete(string term)
	//    var data = await _searchProviderAutoComplete.AutoComplete(term);

The razor page view sends the ajax request using the jQuery autocomplete and processes the result. The data is displayed in a bootstrap 4 card.

@page "{handler?}"
@model SearchAutoCompleteModel
    ViewData["Title"] = "Auto complete suggester";

<fieldset class="form">
    <legend>Search for a person in the search engine</legend>
    <table width="500">
                <input class="form-control" id="autocomplete" type="text" style="width:500px" />

<br />

<div class="card">
    <h5 class="card-header">
        <span id="docName"></span>
        <span id="docFamilyName"></span>
    <div class="card-body">
        <p class="card-text"><span id="docInfo"></span></p>
        <p class="card-text"><span id="docCityCountry"></span></p>
        <p class="card-text"><span id="docWeb"></span></p>

@section scripts
    <script type="text/javascript">
        var items;
        $(document).ready(function () {
                source: function (request, response) {
                        url: "SearchAutoComplete/AutoCompleteSuggest",
                        dataType: "json",
                        data: {
                            term: request.term,
                        success: function (data) {
                            var itemArray = new Array();
                            for (i = 0; i < data.length; i++) {
                                itemArray[i] = {
                                    label: data[i] + " " + data[i].document.familyName,
                                    value: data[i] + " " + data[i].document.familyName,
                                    data: data[i]

                        error: function (data, type) {
                select: function (event, ui) {

The required npm packages are loaded using npm and bundled using the bundle Config. The javascript autocomplete is part of the jquery-ui-dist npm package. Or course if you implement a Vue.JS, React or Angular UI, you would use a different autocomplete lib.

  "version": "1.0.0",
  "name": "",
  "private": true,
  "devDependencies": {
    "bootstrap": "4.6.0",
    "jquery": "3.6.0",
    "jquery-ajax-unobtrusive": "3.2.6",
    "jquery-ui-dist": "^1.12.1",
    "jquery-validation": "1.19.3",
    "jquery-validation-unobtrusive": "3.2.12",
    "popper.js": "^1.16.1"

When the application is started, the search runs as required.

This could also be implemented using the word autocomplete together with the search but returning the results in a table view or something similar.



  1. […] Using Azure Cognitive Search Suggesters in ASP.NET Core and Autocomplete […]

  2. […] Using Azure Cognitive Search Suggesters in ASP.NET Core and Autocomplete (Damien Bowden) […]

  3. […] Using Azure Cognitive Search Suggesters in ASP.NET Core and Autocomplete – Damien Bowden […]

  4. […] Using Azure Cognitive Search Suggesters in ASP.NET Core and Autocomplete […]

Leave a Reply

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

You are commenting using your 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.

%d bloggers like this: