UI Libraries / Autocomplete / getAlgoliaResults

The getAlgoliaResults function lets you query several Algolia indices at once.

Example# A

This example uses the function along with the algoliasearch API client.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import algoliasearch from 'algoliasearch/lite';
import { autocomplete, getAlgoliaResults } from '@algolia/autocomplete-js';

const searchClient = algoliasearch(
  'latency',
  '6be0576ff61c053d5f9a3225e2a90f76'
);

autocomplete({
  // ...
  getSources({ query }) {
    return [
      {
        sourceId: 'products',
        getItems({ query }) {
          return getAlgoliaResults({
            searchClient,
            queries: [
              {
                indexName: 'instant_search',
                query,
                params: {
                  hitsPerPage: 5,
                },
              },
            ],
          });
        },
        // ...
      },
    ];
  },
});

When using getAlgoliaFacets and getAlgoliaResults with the same search client in different sources or plugins, Autocomplete batches all queries into a single network call to Algolia. If you’re using the same search client for different sources or plugins, make sure to use the same instance to leverage the internal cache and batching mechanism.

Parameters# A

searchClient #
type: SearchClient
Required

The initialized Algolia search client.

queries #
type: MultipleQueriesQuery[]
Required

The queries to perform.

queries ➔ queries #

indexName #
type: string
Required

The index name to search into.

query #
type: string

The query to search for.

params #
type: SearchParameters

Algolia search parameters.

These are the default search parameters. You can leave them as is and specify other parameters, or override them.

1
2
3
4
5
{
  "hitsPerPage": 5,
  "highlightPreTag": "__aa-highlight__",
  "highlightPostTag": "__/aa-highlight__"
}
transformResponse #
type: (response: { results: Array<SearchResponse<THit> | SearchForFacetValuesResponse>, hits: MaybeArray<Hit<THit>[]>, facetHits: MaybeArray<FacetHit[]> }) => MaybeArray<Hit<THit>[] | FacetHit[]>

The function to transform the Algolia response before passing it to the Autocomplete state. You have access to the full Algolia results, as well as the pre-computed hits and facet hits. This is useful to manipulate the hits, or store data from the results in the context.

This is the default implementation:

1
2
3
4
5
6
getAlgoliaResults({
  // ...
  transformResponse({ hits }) {
    return hits;
  },
});

Returns# A

The function returns a description with the following interface:

1
2
3
4
5
6
{
  searchClient: SearchClient;
  queries: MultipleQueriesQuery[];
  transformResponse: TransformResponse<THit>;
  execute: Execute<THit>;
}
Did you find this page helpful?