自动完成
Algolia 提供了一个很棒的自动完成库,称为 autocomplete.js (在新标签页中打开),它可以与 Searchkit 一起使用。本指南将向您展示如何使用它。
可以在 此处找到一个可运行的示例。
命中自动完成示例
此示例演示了如何将 autocomplete.js 与 Searchkit 一起使用。它使用来自 autocomplete.js 库的 getAlgoliaResults
函数。
import client from "@searchkit/instantsearch-client";
import {
getAlgoliaResults
} from "@algolia/autocomplete-js";
const autocompleteClient = client({
url: "https://ises-cfw.searchkit.workers.dev"
});
// needed for the autocomplete client to work
autocompleteClient.transporter = {
headers: {
'x-algolia-application-id': 'NULL',
'x-algolia-api-key': 'NULL'
}
}
getSources={({ query, state }) => {
if (!query) {
return [];
}
return [
{
sourceId: "movies",
getItems() {
// using searchkit to get results for the query
return getAlgoliaResults({
autocompleteClient,
queries: [
{
indexName: "imdb_movies",
query,
params: {
query
}
}
],
transformResponse({ hits }) {
const [imdbMoviesHits] = hits;
return imdbMoviesHits;
}
});
},
templates: {
header() {
return (
<Fragment>
<span className="aa-SourceHeaderTitle">Movies</span>
<div className="aa-SourceHeaderLine" />
</Fragment>
);
},
item({ item, components }) {
return <div>{item.title}</div>;
},
noResults() {
return "No movies for this query.";
}
}
}
];
}}
筛选自动完成示例
此示例演示了如何将 autocomplete.js 与筛选一起使用。它使用来自 autocomplete.js 库的 getAlgoliaFacets
函数。
它查询 actors
筛选并返回前 5 个结果。如果用户输入查询,它将返回前 3 个结果。
import client from "@searchkit/instantsearch-client";
import {
getAlgoliaFacets
} from "@algolia/autocomplete-js";
const autocompleteClient = client({
url: "https://ises-cfw.searchkit.workers.dev"
});
// needed for the autocomplete client to work
autocompleteClient.transporter = {
headers: {
'x-algolia-application-id': 'NULL',
'x-algolia-api-key': 'NULL'
}
}
function createCategoriesPlugin({
autocompleteClient
}) {
return {
getSources({ query }) {
return [
{
sourceId: "actorsPlugin",
getItems() {
return getAlgoliaFacets({
searchClient,
queries: [
{
indexName: "imdb_movies",
facet: "actors",
params: {
facetName: "actors",
facetQuery: query,
maxFacetHits: query ? 3 : 5
}
}
]
});
},
templates: {
header() {
return (
<Fragment>
<span className="aa-SourceHeaderTitle">Actors</span>
<div className="aa-SourceHeaderLine" />
</Fragment>
);
},
item({ item, components }) {
return (
<div className="aa-ItemWrapper">
<div className="aa-ItemContent">
<div className="aa-ItemContentBody">
<div className="aa-ItemContentTitle">{item.label}</div>
</div>
</div>
</div>
);
}
}
}
];
}
};
}