Including multiple result types
Following this tutorial requires an Algolia application with the Query Suggestions feature enabled.
Query suggestions are one aspect of rich multi-category search experiences. For example, if you search for something in your email inbox, your results could contain not just email threads, but also contacts, attachments, and more. Ecommerce stores often show query suggestions, products, blog posts, brands, and categories all in one autocomplete.
It’s best to display different results types in different sections. This helps users understand what the items are and what happens when they choose one.
The Autocomplete library lets you mix different item types in one autocomplete and customize their display.
To do so you need to several sources in the getSources
option.
This tutorial outlines how to combine static predefined items, recent searches and Query Suggestions.
Using plugins for each source makes the code modular, reusable, and sharable.
However, instead of using plugins, you could add different sources directly in getSources
.
Before you begin
This guide assumes that you know HTML, CSS, and JavaScript and that you have existing HTML with an input element where you want to insert the autocomplete drop-down menu.
It also assumes that you have an Algolia application with a populated Query Suggestions index.
Starter code
Begin by adding the following Autocomplete starter code. Create a file called index.js
in your src
directory.
1
2
3
4
5
6
7
import { autocomplete } from '@algolia/autocomplete-js';
autocomplete({
container: '#autocomplete',
plugins: [],
openOnFocus: true,
});
This starter code assumes you want to insert the Autocomplete menu into a DOM element with autocomplete
as an id
.
Change the container
to match your markup. Setting openOnFocus
to true
ensures that the drop-down menu appears as soon as a user focuses the input.
For now, plugins
is an empty array, but you’ll learn how to create and add plugins for predefined items, recent searches, and Query Suggestions next.
Add predefined items
A popular search pattern for autocomplete menus shows predefined search terms as soon as a user clicks on the search box and before they begin typing anything. This provides a guided experience and exposes users to helpful resources or other content you want them to see.
This tutorial describes how to create a plugin to show static, predefined items. In particular, it exposes helpful links users may want to refer to.
Create a predefined items plugin
Begin by creating a predefinedItemsPlugin.js
file in your src
directory, with the following code:
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
34
const predefinedItems = [
{
label: 'Documentation',
url: 'https://www.algolia.com/doc/ui-libraries/autocomplete/introduction/what-is-autocomplete/',
},
{
label: 'GitHub',
url: 'https://github.com/algolia/autocomplete',
},
];
export const predefinedItemsPlugin = {
getSources() {
return [
{
sourceId: 'predefinedItemsPlugin',
getItems({ query }) {
if (!query) {
return predefinedItems;
}
return predefinedItems.filter((item) =>
item.label.toLowerCase().includes(query.toLowerCase())
);
},
getItemUrl({ item }) {
return item.url;
},
templates: {
// ...
},
},
];
},
};
predefinedItemsPlugin
has a similar signature as any other autocomplete implementation:
it uses the getSources
option to return an array of items to display.
Each object in the array defines where to get items using getItems
.
An Autocomplete plugin is an object that implements the AutocompletePlugin
interface.
For more information, see Building your own plugin.
In this example, getItems
returns a filtered array of predefinedItems
.
The code filters the array to return items that match the query, if it exists.
If it doesn’t, it returns the entire array.
You can return whatever predefined items you like and format them accordingly.
For example, suppose you want to show trending search items instead of helpful links.
Use getItems
to retrieve them from another source, including an asynchronous API.
The getItemUrl
function defines how to get the URL of an item.
In this case, since it’s an attribute on each object in the predefinedItems
array, just return the attribute.
Use getItemUrl
to add keyboard navigation to the autocomplete menu.
Users can scroll through items in the menu with the up and down keys.
When they hit Enter on one of the predefinedItems
or any source that includes getItemUrl
, it opens the URL retrieved from getItemUrl
.
Templates define how to display each section of the autocomplete, including the header
, footer
, and each item
.
Templates can return any valid virtual DOM element (VNode).
This example defines how to display each predefined item with the item
template and gives a header
for the entire section.
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// ...
export const predefinedItemsPlugin = {
getSources() {
return [
{
sourceId: 'predefinedItemsPlugin',
getItems({ query }) {
if (!query) {
return predefinedItems;
}
return predefinedItems.filter((item) =>
item.label.toLowerCase().includes(query.toLowerCase())
);
},
getItemUrl({ item }) {
return item.url;
},
templates: {
header({ items, html }) {
if (items.length === 0) {
return null;
}
return html`<span class="aa-SourceHeaderTitle">Links</span>
<div class="aa-SourceHeaderLine" />`;
},
item({ item, html }) {
return html`<a class="aa-ItemLink" href="${item.url}">
<div class="aa-ItemIcon aa-ItemIcon--noBorder">
<svg
width="18"
height="18"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path
d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"
/>
<polyline points="15 3 21 3 21 9" />
<line x1="10" y1="14" x2="21" y2="3" />
</svg>
</div>
<div class="aa-ItemContent">
<div class="aa-ItemContentTitle">${item.label}</div>
</div>
</a>`;
},
},
},
];
},
};
Add the predefined items plugin to the autocomplete
Import the newly created predefinedItemsPlugin
and add it toplugins
in index.js
.
Once you’ve done that, the file should look like this:
1
2
3
4
5
6
7
8
import { autocomplete } from '@algolia/autocomplete-js';
import { predefinedItemsPlugin } from './predefinedItemsPlugin';
autocomplete({
container: '#autocomplete',
plugins: [predefinedItemsPlugin],
openOnFocus: true,
});
Now, as soon as a user clicks on the search box, these predefined items appear. Once they begin typing, only predefined items that contain the query remain.
Add recent searches and Query Suggestions
You can add recent searches and Query Suggestions using out-of-the-box plugins.
Create a recent searches plugin
Use the out-of-the-box createLocalStorageRecentSearchesPlugin
function to create a recent searches plugin:
1
2
3
4
5
6
import { createLocalStorageRecentSearchesPlugin } from '@algolia/autocomplete-plugin-recent-searches';
const recentSearchesPlugin = createLocalStorageRecentSearchesPlugin({
key: 'RECENT_SEARCH',
limit: 5,
});
The key
can be any string and is required to differentiate search histories if you have several Autocomplete experiences on one page.
The limit
defines the maximum number of recent searches to display.
Create a Query Suggestions plugin
If you don’t have a Query Suggestions index yet, create one. Use the demo app credentials and index name provided in this tutorial.
Use the out-of-the-box createQuerySuggestionsPlugin
function to create a Query Suggestions plugin.
It requires an Algolia search client initialized with an Algolia application ID and API key and an indexName
.
The indexName
is the name of your Query Suggestions index.
1
2
3
4
5
6
7
8
9
10
import { createQuerySuggestionsPlugin } from '@algolia/autocomplete-plugin-query-suggestions';
const appId = 'latency';
const apiKey = '6be0576ff61c053d5f9a3225e2a90f76';
const searchClient = algoliasearch(appId, apiKey);
const querySuggestionsPlugin = createQuerySuggestionsPlugin({
searchClient,
indexName: 'instant_search_demo_query_suggestions',
});
Coordinate Query Suggestions with other sources
When instantiating your Query Suggestions plugin, you can optionally pass a getSearchParams
function to apply Algolia query parameters to the suggestions returned from the plugin.
This is helpful if you need to coordinate your Query Suggestions with other sections displayed in the autocomplete, like recent searches.
For example, if you’d like to show a combined total of 10 search terms (recent searches plus Query Suggestions), you can indicate this:
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
import { autocomplete } from '@algolia/autocomplete-js';
import { createLocalStorageRecentSearchesPlugin } from '@algolia/autocomplete-plugin-recent-searches';
import { createQuerySuggestionsPlugin } from '@algolia/autocomplete-plugin-query-suggestions';
const recentSearchesPlugin = createLocalStorageRecentSearchesPlugin({
key: 'RECENT_SEARCH',
limit: 5,
});
const appId = 'latency';
const apiKey = '6be0576ff61c053d5f9a3225e2a90f76';
const searchClient = algoliasearch(appId, apiKey);
const querySuggestionsPlugin = createQuerySuggestionsPlugin({
searchClient,
indexName: 'instant_search_demo_query_suggestions',
getSearchParams() {
return recentSearchesPlugin.data.getAlgoliaSearchParams({
hitsPerPage: 10,
}),
});
autocomplete({
// ...
});
This shows up to five recent searches (set by the limit
parameter) and up to 10 total search terms.
If there’s only one recent search in local storage, the autocomplete displays nine Query Suggestions, assuming that there are nine relevant suggestions.
Separate result types
When using sources other than just recent and suggested searches, it’s best to label the different result types with headers
.
For the createLocalStorageRecentSearchesPlugin
and createQuerySuggestionsPlugin
plugins, use the transformSource
option to do this.
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import { autocomplete } from '@algolia/autocomplete-js';
import { createLocalStorageRecentSearchesPlugin } from '@algolia/autocomplete-plugin-recent-searches';
import { createQuerySuggestionsPlugin } from '@algolia/autocomplete-plugin-query-suggestions';
// ...
const recentSearchesPlugin = createLocalStorageRecentSearchesPlugin({
// ...
transformSource({ source }) {
return {
...source,
templates: {
...source.templates,
header({ items, html }) {
if (items.length === 0) {
return null;
}
return html`<span class="aa-SourceHeaderTitle">Recent</span>
<div class="aa-SourceHeaderLine" />`;
},
},
};
},
});
const querySuggestionsPlugin = createQuerySuggestionsPlugin({
// ...
transformSource({ source }) {
return {
...source,
templates: {
...source.templates,
header({ items, html }) {
if (items.length === 0) {
return null;
}
return html`<span class="aa-SourceHeaderTitle">Suggestions</span>
<div class="aa-SourceHeaderLine" />`;
},
},
};
},
});
autocomplete({
// ...
});
Add plugins
All that’s left to do is add all your plugins to your Autocomplete instance:
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 { autocomplete } from '@algolia/autocomplete-js';
import { predefinedItemsPlugin } from './predefinedItemsPlugin';
import { createLocalStorageRecentSearchesPlugin } from '@algolia/autocomplete-plugin-recent-searches';
import { createQuerySuggestionsPlugin } from '@algolia/autocomplete-plugin-query-suggestions';
const recentSearchesPlugin = createLocalStorageRecentSearchesPlugin({
key: 'RECENT_SEARCH',
limit: 5,
});
const appId = 'latency';
const apiKey = '6be0576ff61c053d5f9a3225e2a90f76';
const searchClient = algoliasearch(appId, apiKey);
const querySuggestionsPlugin = createQuerySuggestionsPlugin({
searchClient,
indexName: 'instant_search_demo_query_suggestions',
getSearchParams() {
return recentSearchesPlugin.data.getAlgoliaSearchParams({
hitsPerPage: 10,
});
},
});
autocomplete({
container: '#autocomplete',
plugins: [
recentSearchesPlugin,
querySuggestionsPlugin,
predefinedItemsPlugin,
],
openOnFocus: true,
});
This creates a basic multi-source autocomplete. Try it out below:
Next steps
This tutorial combined three sources in one autocomplete. Depending on your use case, you might want to add more or different ones than the ones included here. Regardless of what you use for your sections, the method is the same: provide a different a source for each.
You may also choose to style your multi-source autocomplete differently by creating a horizontal layout or further differentiating how to display each source type.