Get query suggestions

This is for:

Developer
In this article

You can request basic query expression (q) completions from a Coveo Machine Learning (Coveo ML) Query Suggestions (QS) model by sending a GET or POST HTTP request to https://platform.cloud.coveo.com/rest/search/v2/querySuggest.

The Search API query suggestion route supports several parameters which you can include either in the query string of a GET request, or in the JSON body of a POST request (see QS Parameters).

When using an OAuth2 token to authenticate a GET or POST HTTP request to the Search API query suggestion route, you must specify the unique identifier of the target Coveo organization by including the organizationId argument in the query string of your request.

  1. Requesting query suggestions using the GET method:

    GET https://platform.cloud.coveo.com/rest/search/v2/querySuggest?locale=en&q=twa&searchHub=BookstoreSearch HTTP/1.1
     
    Accept: application/json
    Authorization: Bearer **********-****-****-****-************
    
  2. Requesting query suggestions using the POST method:

    POST https://platform.cloud.coveo.com/rest/search/v2/querySuggest HTTP/1.1
     
    Content-Type: application/json
    Accept: application/json
    Authorization: Bearer **********-****-****-****-************
    

    Payload

    {
      "locale": "en",
      "q": "twa",
      "searchHub": "BookstoreSearch"
    }
    

    200 OK response body (excerpt)

    {
      "completions": [
        {
          "executableConfidence": 1,
          "expression": "mark twain",
          "highlighted": "[mark] {twa}[in]",
          "score": 14.525258530973204
        },
        {
          "executableConfidence": 0.6666666666666666,
          "expression": "[wes]{twa}[rd] [ho]",
          "highlighted": "",
          "score": 8.50548085208594
        },
        {
          "executableConfidence": 0.5,
          "expression": "hot water music",
          "highlighted": "[hot] (wat)[er] [music]",
          "score": 7.107770631785241
        },
        ...
      ]
    }
    
  • If the query suggestion request is routed to a query pipeline with no associated Coveo ML QS model, the request will return an empty completions array.

  • In a completions array item:

    • The score property value only has relative significance within the same completions array.

      For example, a suggestion with a score of 14.811407079917723 in the completions array of response A isn’t necessarily less relevant than a suggestion with a score of 24.325728875625282 in the completions array of response B.

    • The highlighted property uses the following logic:

      • Characters between curly braces (e.g., {cat}) indicate an exact match with q.

      • Characters between square braces (e.g., [cher]) indicate completions.

      • Characters between parentheses (e.g., (act)) indicate corrections to q.

    • The executableConfidence property contains a floating-point value between 0 and 1 indicating how “convinced” Coveo ML is that performing a query with this suggestion as a basic query expression will return relevant results. The threshold from which Coveo ML considers a query suggestion executable is 0.8.

QS parameters

This section provides reference documentation for the available parameters when sending a GET or POST HTTP request to the Search API query suggestion endpoint.

actionsHistory (array)

The query and page view actions previously made by the current user.

Coveo Machine Learning content recommendations models use this information to provide contextually relevant output.

Note: Page view actions are typically populated by the coveo.analytics.js script.

analytics ()

Contextual information about the user performing the request and the request itself.

Coveo Machine Learning models may use this information to provide contextually relevant output.

Available parameters:

  • userId (string): The ID of the logged user. If not present, the id is obtained from the authentication token.
  • clientId (string): A GUID which represents the current client. The clientId and deviceId replace the deprecated visitorId. For compatibility, the cookie and local storage values are still named coveo_visitorId.
  • deviceId (string): The name of the device that the end user is using. It has to be explicitly passed from native mobile apps. The clientId and deviceId replace the deprecated visitorId.
  • documentLocation (string): The URL of the current page or component. If not present, the referrer is obtained from the Referer header. This information can be obtained from coveo.analytics.js.
  • documentReferrer (string): Typically the URL of the page that linked to the search interface from which the request originates (e.g., in JavaScript, this would correspond to the document.referrer value). This information can be obtained from coveo.analytics.js.
  • pageId (string): A GUID representing the page ID. This information can be obtained from coveo.analytics.js.
  • userIp (string): The user IP. If not present, the IP is obtained from the X-Forwarded-For and Forwarded headers. This information is required when endpoints are behind a proxy.
  • clientRequestId (string): A GUID generated by the client representing the current request. This information is used to identify operations across different apis related to the same request.
  • clientTimestamp (string): Client ISO 8601 timestamp with milliseconds.
  • userAgent (string): The user agent of the request. If not present, the user agent is obtained from the User-Agent header. This information is required when endpoints are behind a proxy.

Examples:

  • {"userId": "user@email.com", "clientId": "6d148f06-5f15-4639-81b4-792a9b94eb5f", "deviceId": "Chrome"}
  • {"clientTimestamp": "2020-09-09T19:00:45.603-04:00", "userAgent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36"}

context (object)

The custom context information to send along with the request. Must be a dictionary of key-value pairs (JSON) where each key is a string, and each value is either a string or an array of strings.

Coveo Machine Learning models may use this information to provide contextually relevant output. Moreover, this information can be referred to in query expressions and QPL statements by using the $context object.

Note: When logging a Search usage analytics event for a query, the customData field of that event should include the same data as the context parameter of the query. However, each context key included in customData must be prefixed by context_ (e.g., the userRoles key in context becomes context_userRoles in customData).

See also the referrer parameter.

Example {"userAgeRange":"25-35","userRoles":["PremiumCustomer","ProductReviewer"]}

count (integer [int32])

The desired number of query suggestions.

debug (boolean)

Whether to force a successful response to include debug information.

Notes:

  • Debug information can only appear in responses in the JSON format (see the format parameter).
  • Avoid setting this parameter to true in production, as it has a negative impact on query performance.

Default: false

enableWordCompletion (boolean)

Whether to attempt to complete the last word of the current basic query expression (see the q parameter) and boost the ranking score of the resulting expression so that it is returned as the first query suggestion.

format (string)

The format of a successful response.

  • Use json to get the response in the JSON format.
  • Use opensearch-atom or opensearch-rss to get the results in an OpenSearch format (XML).
  • Use xlsx to generate an Excel file containing the results (binary).

Note: Debug information (see the debug parameter) can only appear in a response in the JSON format.

Default: json

index (string)

The identifier of the index mirror to forward the request to. See also the indexToken parameter.

If you do not specify an index (or indexToken) value, any index mirror could be used.

Note: Passing an index (or indexToken) value has no effect when the results of a specific request can be returned from cache (see the maximumAge parameter).

Example: myorg-nvoqun-Indexer1-pbi2nbuw

indexToken (string)

The Base64 encoded identifier of the index mirror to forward the request to. See also the index parameter.

If you do not specify an indexToken (or index) value, any index mirror could be used.

Note: Passing an indexToken (or index) value has no effect when the results of a specific request can be returned from cache (see the maximumAge parameter).

Example: ZXhhbXBsZWluZGV4bWlycm9yLS4uLg==

indexType (string)

The type of index against which to execute the query. Must correspond to an index that has been configured for the target Coveo Cloud organization.

Default: coveo

isGuestUser (boolean)

Whether the current user is anonymous.

Coveo Machine Learning models may use this information to provide contextually relevant output.

Note: When logging a Search usage analytics event for a query, the anonymous field of that event should be set to the isGuestUser value of the query.

Default: false

locale (string)

The locale of the current user. Must comply with IETF’s BCP 47 definition.

Coveo Machine Learning models use this information to provide contextually relevant output. Moreover, this information can be referred to in query expressions and QPL statements by using the $locale object.

Note: When logging a Search usage analytics event, the language field of that event should match the language part of the locale value of the query (e.g., en-US in locale becomes en in language).

Example: en-US

logicalIndex (string)

The identifier for a logical group of indexes that have been configured to include documents form the same sources.

If you do not specify a logicalIndex value, the default grouping will be used, typically including all indexes.

Example: webcontentonly

maximumAge (integer [int32])

The maximum age of cached results, in milliseconds.

If the results of a specific request are available in the cache, and if those results are no older than the maximumAge value, the service returns those results rather than forwarding a new query to the index.

Note: This parameter is automatically overridden when staticQuery is set to true.

Default: -1 (which corresponds to the internal default value (15 minutes)

maximumTimeoutMs (integer [int32])

The maximum number of milliseconds to allow the request to last before timing out. Maximum: 16000

Minimum/Default: 0, meaning that Coveo determines the most appropriate timeout to use.

mlParameters (object)

A map of options to pass to the Coveo ML models associated with the request’s target query pipeline.

Available parameters:

  • considerUserContext (boolean): Whether the models should attempt to leverage the context object of the request to personalize their output. Applies to CR models only. Default is true.
  • maxActionsHistoryItemsToConsider (unsigned integer): The maximum number of items in the actionsHistory array of the request that should be taken into account by the models. Applies to CR models only. By default, all actionsHistory items are considered.
  • num (unsigned integer): The maximum number of recommendations/suggestions to request from the models. Must be in range [1, 50], if specified. Applies to ART, CR, and QS models. Default depends on model configuration.
  • padding (string enum): The kind of padding the models should complete their output with, if their maximum number of recommendations/suggestions (i.e., num) has not been reached. Applies to CR models only. Allowed values are popular (i.e., pad recommendations with all time most popular items) and trending (i.e., pad recommendations with items that have recently been increasingly popular). By default, no padding applies.
  • wordSelection (string): The ITD keyword selection options the models should use. Applies only to ART models with ITD enabled. If specified, must be a string in the format option:value. The only available option is wordsKept (i.e., the maximum number of lq keywords to inject in q); its default value is 5.
  • minNumberOfWords (unsigned integer): The minimum number of words a query suggestion may contain to be returned by the model. Applies to QS models only. Must be in range [1, 10] Default is 1, which implies that the model will return all candidates.
  • itemId (string): The unique identifier (e.g., SKU) of a product to get recommendations for. Only applies when querying a Product Recommendations model with an association strategy considering a single item as an input.
  • itemIds (array of strings): The unique identifiers (e.g., SKUs) of the products to get recommendations for. Only applies when querying a Product Recommendations model with an association strategy considering multiple items as an input.
  • categoryFilter (string): The name of a category of products to get recommendations for.
  • brandFilter (string): The name of a brand of products to get recommendations for.
  • filters (map of strings): The dimensions along with the values to be used at query time by the model as filters for potential suggestions. Only applies to Automatic relevance Tuning, Query Suggestions, or Dynamic Navigation Experience models that don’t use the default filterFields advanced parameter values. Example: "filters": { "originContext": "<MY-VALUE>", "originLevel2": "<MY-VALUE>" }.

Examples:

  • {"num": 3, "padding": "trending", "maxActionsHistoryItemsToConsider": 10, "considerUserContext": false}
  • {"wordSelection": "wordsKept:4"}

pipeline (string)

The name of the query pipeline to use for this request (bypassing its conditions, if it has any).

You can pass an empty pipeline value to use an empty query pipeline (i.e., ?pipeline= or "pipeline": "").

If a query does not contain the pipeline parameter, the first query pipeline whose conditions are met by the request is used (query pipelines without conditions are not evaluated). Should the request fail to meet the conditions of each evaluated query pipeline, the default query pipeline of the target Coveo Cloud organization is used (bypassing its conditions, if it has any).

Notes:

  • This parameter will be overridden if the search request is authenticated by a search token that enforces a specific pipeline, or a searchHub that routes queries to a specific pipeline via a query pipeline condition.
  • For reporting purposes, when logging a Search usage analytics event for a query, the queryPipeline field of that event should be set to the pipeline value of the query (or to the "default" string, if no pipeline value was specified in the query).

See also Managing Query Pipelines.

Example: CustomerQueryPipeline

q (string)

The basic query expression, typically the keywords entered by the end user in a query box.

Example: Coveo "Cloud V2" platform

recommendation (string)

The identifier of the recommendation interface from which the request originates.

Coveo Machine Learning content recommendations models may use this information to provide contextually relevant output.

Example: RecommendedProducts

referrer (string)

The third level of origin of the request, typically the URL of the page that linked to the search interface from which the request originates (e.g., in JavaScript, this would correspond to the document.referrer value).

Coveo Machine Learning models may use this information to provide contextually relevant output.

Note: When logging a Search usage analytics event for a query, the originLevel3 field of that event should be set to the referrer value of the query, if specified.

See also the context parameter.

Example: http://www.example.com/

searchHub (string)

The first level of origin of the request, typically the identifier of the graphical search interface from which the request originates.

Coveo Machine Learning models use this information to provide contextually relevant output.

Notes:

  • This parameter will be overridden if the search request is authenticated by a search token that enforces a specific searchHub.
  • When logging a Search usage analytics event for a query, the originLevel1 field of that event should be set to the value of the searchHub search request parameter.

See also the tab parameter.

Example: CustomerPortal

tab (string)

The second level of origin of the request, typically the identifier of the selected tab in the graphical search interface from which the request originates.

Coveo Machine Learning models use this information to provide contextually relevant output.

Note: When logging a Search usage analytics event for a query, the originLevel2 field of that event should be set to the tab value of the query (or to the "default" string, if no tab value was specified in the query).

See also the searchHub parameter.

Example: ForumTab

timezone (string)

The tz database identifier of the time zone to use to correctly interpret dates in the query expression and result items.

If not specified, the default time zone of the server hosting the index is used.

Note: While no Coveo Machine Learning model uses this information, it can nevertheless affect the ranking scores (and thus, potentially the order) of result items, as ranking expressions may be based on time constants.

Example: America/New_York

visitorId (string)

A GUID which represents the current user, who can either be authenticated or anonymous.

visitorId is deprecated and has been replaced by clientId in newer versions of the Coveo UI libraries. For compatibility, the new first-party cookie and local storage values are still named coveo_visitorId.

For older versions of the JavaScript Search Framework, the visitor ID is generated by the Coveo Usage Analytics service and stored in a non-expiring third-party cookie. Note: Third-party cookies have also been deprecated. This is unrelated to the deprecation of visitorId.

Example: 5cb98953-9c13-42ff-8176-e6fcba6a50bf

Troubleshooting

If your QS model isn’t behaving as expected, this may be due to a mismatch between the searchHub value used in your Search API requests and the originLevel1 value used when logging events for the target search interface through the Coveo Usage Analytics (Coveo UA) Write API. It’s important that those values match in any given search interface, since the Coveo ML service uses them as filter fields.

You have a search interface for books, and another one for movies.

On the usage analytics side, when logging events in those search interfaces, the originLevel1 value specified in your requests is, respectively, BookstoreSearch and MovieStoreSearch.

On the Search API side, this translates into very distinctive behavior from one searchHub to another. You make the following request:

POST https://platform.cloud.coveo.com/rest/search/v2/querySuggest HTTP/1.1
 
Content-Type: application/json
Accept: application/json
Authorization: Bearer **********-****-****-****-************

Payload

{
  "q": "Dost",
  "searchHub": "BookstoreSearch"
}

The Search API returns the following completions, where the Dostoevsky suggestion is executable and highly recommended:

200 OK response body (excerpt)

{
  "completions": [
    {
      "executableConfidence": 1,
      "expression": "Dostoevsky",
      "highlighted": "{Dost}[oevsky]",
      "score": 56.135864235791246
    },
    ...
  ]
}

You make the following request to the Search API:

POST https://platform.cloud.coveo.com/rest/search/v2/querySuggest HTTP/1.1
 
Content-Type: application/json
Accept: application/json
Authorization: Bearer **********-****-****-****-************

Payload

{
  "q": "Dost",
  "searchHub": "MovieStoreSearch"
}

The Search API returns the following completions, where Dosti (a highly successful Hindi film) is executable and highly recommended, and where Dostoevsky doesn’t figure at all:

200 OK response body (excerpt)

{
  "completions": [
    ...
    {
      "executableConfidence": 1,
      "expression": "Dosti",
      "highlighted": "{Dost}[i]",
      "score": 35.183255413846215
    },
    ...
  ]
}

Hence, when in the BookstoreSearch search interface, it’s very important to pass the "searchHub": "BookstoreSearch" for the relevant query suggestion Dostovesky to be returned, instead of Hindi films.

Analogous remarks hold for the tab value used in your Search API requests and the originLevel2 value used in your Coveo UA Write requests.