Add Autocomplete to Your Application

  • how-to
March 23, 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 have the Search Service enabled on a node in your database. For more information about how to deploy a new node and Services on your database, see Manage Nodes and Clusters.

  • You have a bucket with scopes and collections in your database. For more information about how to create a bucket, see Create a Bucket.

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

  • Your user account has the Search Admin role for the bucket where you created the Search index.

  • You have the hostname or IP address for the node in your database where you’re running the Search Service. For more information about where to find the IP address for your node, see List Cluster Nodes.

Procedure

To add autocomplete with the Search 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: