Create a search interface with the Query API

The Query API provides search and suggest methods for building a search interface or embedding search results in an application.

For web applications with minimal requirements, consider using search widget. For more information, see Create a search interface with the search widget

Build a search interface

Buiding a minimal search interface requires several steps:

  1. Configure a search application
  2. Generate OAuth credentials for the application
  3. Query the index
  4. Display the query results

You can further enhance the search interface with features such as paging, sorting, filtering, facets, and auto-suggest.

Configure a search application

You must create at least one search application to associate with each search interface you create. A search application provides the default parameters for a query, such as the data sources to include, the sort order, filters, and facets to request. If needed, you can override these parameters using the query API.

For more information about search applications, refer to Create a custom search experience.

Generate OAuth credentials for the application

In addition to the steps in Configure access to the Google Cloud Search REST API, you also must generate OAuth credentials for the web application. The type of credentials you create depends on the context the API is used in.

Use the credentials to request authorization on behalf of the user. Use the scope https://www.googleapis.com/auth/cloud_search.query when requesting authorization.

For additional information about OAuth options and client libaries, see Google Identity Platform

Query the index

Use the search method to perform searches against the index.

Every request must include two pieces of information: a text query to match items against and a searchApplicationId identifying the ID for the search application to use.

The following snippet shows a query to movie data source for the movie Titanic:

{
  "query": "titanic",
  "requestOptions": {
    "searchApplicationId": "searchapplications/<search_app_id>"
  },
}

Display query results

At a minimum, search interfaces are expected to display the item title as well as a link to the original item. You can further enhance the display of search results by leveraging additional information present in search results such as the snippet and metadata.

Highlight snippets

For returned items containing indexed text or HTML content, a snippet of the content is returned. This content helps users determine the relevancy of the returned item.

If query terms are present in the snippet, one or more match ranges identifying the location of the terms are also returned.

Use the matchRanges to highlight the matching text when rendering the results. The following javascript example converts the snippet into HTML markup with each matching range wrapped in a <span> tag.

function highlightSnippet(snippet) {
  let text = snippet.snippet;
  let formattedText = text;
  if (snippet.matchRanges) {
    let parts = [];
    let index = 0;
    for (let match of snippet.matchRanges) {
      let start = match.start || 0; // Default to 0 if omitted
      let end = match.end;
      if (index < start) { // Include any leading text before/between ranges
        parts.push(text.slice(index, start));
      }
      parts.push('<span class="highlight">');
      parts.push(text.slice(start, end));
      parts.push('</span>');
      index = end;
    }
    parts.push(text.slice(index)); // Include any trailing text after last range
    formattedText = parts.join('');
  }
  return formattedText;
}

Given the snippet:

{
  "snippet": "This is an example snippet...",
  "matchRanges": [
    {
      "start": 11,
      "end": 18
    }
  ]
}

The resulting HTML string is:

This is an <span class="highlight">example</span> snippet...

Display metadata

Use the metadata field to display additional information about the returned item that may be relevant to users. The metadata field includes the createTime and updateTime of the item as well as any returnable structured data associated with the item.

To display the structured data, use the displayOptions field. The displayOptions field contains the display label for the object type and a set of metalines. Each metaline is an array of display labels and value pairs as configured in the schema.

Retrieve additional results

To retrieve additional results, set the start field in the request to the desired offset. You can adjust the size of each page with the pageSize field.

To display the number of returned items or to display paging controls to page through returned items, use the resultCount field. Depending on the size of the result set, either the actual value or an estimated value is provided.

Sort results

Use the sortOptions field to specify the order of returnd items. The sortOptions value is an object with two fields:

  • operatorName — an operator for the structured data property to sort by. For properties with multiple operators, you can only sort using the main equality operator.
  • sortOrder — the direction to sort, either ASCENDING or DESCENDING.

Relevance is also used as the secondary sort key. If no sort order is specified in a query, results are ranked only by relevance.

"sortOptions": {
  "operatorName": "priority",
  "sortOrder": "DESCENDING"
}

Add filters

In addition to query expressions, you can further restrict results by applying filters. You can specify filters both in the search application as well as in the search request.

To add filters in a request or search application, add the filter in the dataSourceRestrictions.filterOptions[] field.

There are 2 primary ways to further filter a data source:

  • Object filters, via the filterOptions[].objectType property — restricts matching items to the specified type as defined in a custom schema.
  • Value filters — restricts matching items based on a query operator and supplied value.

Composite filters allow combining multiple value filters into logical expressions for more complex queries.

In the movie schema example, you could apply an age constraint based on the current user and restrict the available movies based on the MPAA rating.

{
  "query": "adventure",
  "requestOptions": {
    "searchApplicationId": "<search_app_id>"
  },
  "dataSourceRestrictions": [
    {
      "source": {
        "name": "datasources/<data_source_id>"
      },
      "filterOptions": [
        {
          "objectType": "movie",
          "filter": {
            "compositeFilter": {
              "logicOperator": "AND"
              "subFilters": [
                {
                  "compositeFilter": {
                  "logicOperator": "OR"
                  "subFilters": [
                    {
                      "valueFilter": {
                        "operatorName": "rated",
                        "value": {
                          "stringValue": "G"
                        }
                      }
                    },
                    {
                      "valueFilter": {
                        "operatorName": "rated",
                        "value": {
                          "stringValue": "PG"
                        }
                      }
                    }
                  ]
                }
              ]
            }
          }
        }
      ]
    }
  ]
}

Refine results with facets

Facets are indexed properties that represent categories for refining search results. Use facets to help users interactively refine their queries and find relevant items faster.

Facets can be defined in your search application and overridden by settings in your query.

When requesting facets, Cloud Search computes the most frequent values for the requested properties among the matching items. These values are returned in the response. Use these values to construct filters that narrow the results on subsequent queries.

The typical interaction pattern with facets is:

  1. Make an initial query specifying which properties to include in the facet results.
  2. Render the search and facet results.
  3. User selects one or more facet values to refine the results.
  4. Repeat the query with a filter based on the selected values.

For example, to enable refinement of movie queries by year and MPAA rating, include the facetOptions property in the query.

"facetOptions": [
  {
    "sourceName": "datasources/<data_source_id>",
    "operatorName": "year"
  },
  {
    "sourceName": "datasources/<data_source_id>",
    "operatorName": "rated"
  }
]

Interpreting facet buckets

The facetResults property in the response includes an entry for each requested property. For each property, a list of values or ranges, called buckets are provided. The most frequently occuring values appear first.

When a user selects one or more values to filter on, construct a new query with the selected filters and query the API again.

Add suggestions

Use the suggest API to provide auto-completion for queries based on the user's personal query history as well as contacts and their document corpus.

For example, the following call gives suggestions for the partial phrase jo.

{
  "query": "jo",
  "requestOptions": {
    "searchApplicationId": "<search_app_id>",
    "peoplePhotoOptions": {
      "peoplePhotoUrlSizeInPx": 32
    },
    "timeZone": "America/Denver"
  }
}

You can then display the resulting suggestions as appropriate for your application.

Send feedback about...

Cloud Search
Cloud Search