A newer version of this documentation is available.

View Latest

Add Autocomplete to Your Application

  • how-to
March 16, 2025
+ 12
Use autocomplete to add suggestions for a user’s Search query as they type in your application.

After you create and configure a Search index that supports autocomplete, configure your application to return results from the Search Service.

Prerequisites

  • You’ve deployed the Search Service on a node in your database.

  • You have a bucket with scopes and collections in your database.

  • Your user account has the Search Admin role for the bucket where you want to create the index.

  • You’ve created a compatible Search index. For more information, see Configure an Autocomplete Search Index.

Procedure

To add autocomplete with the Serach Service to your application:

  1. To test that your Search index was configured correctly, do one of the following:

    1. Run a Search query from the REST API with 2-8 characters in the query property.

    2. Run a Search query from the Web Console with 2-8 characters in the Search field.

    For example, with the travel-sample bucket, you could enter the strings Be, Bea, Beau, and Beauf to find a document with the text Beaufort Hotel.

  2. Configure your application to return results from the Search Service.

    The following examples simulate a user typing an input string and return search results for each partial string:

    csharp
    using Couchbase; using Couchbase.Search.Queries.Simple; await using var cluster = await Cluster.ConnectAsync(new ClusterOptions { ConnectionString = "CB_HOSTNAME", UserName = "CB_USERNAME", Password = "CB_PASSWORD", Buckets = new List<string>{"travel-sample"} }.ApplyProfile("wan-development")); var searchString = "Beaufort Hotel"; for (var i = 2; i <= 8; i++) { var lettersEntered = searchString.Substring(0, i); Console.WriteLine($"Input <{lettersEntered}>, len: {lettersEntered.Length}"); await FtsMatchPrefix(lettersEntered); } async Task FtsMatchPrefix(string letters) { try { var results = await cluster.SearchQueryAsync("e-ngram-2-8", new QueryStringQuery(letters), options => { options.Limit(8); options.Fields("name"); }); results.Hits.ToList().ForEach(row => { Console.WriteLine($"{row.Id}, {row.Fields}"); }); Console.WriteLine(results); } catch (Exception e) { Console.WriteLine(e); } }

Next Steps

After you add autocomplete to your application, to improve your search results, you can: