Algolia是一个网站搜索服务。很多网站都使用此搜索服务,Algolia具有即时性、可定制性(用户可以随自己喜好定制自己的搜索界面)、还有AI搜索,能及时返回搜索结果,并对搜索结果进行及时的匹配、高亮。可以去Hello Programming的搜索界面体验。
1.注册Algolia账号
先去Algolia官网注册一个账号。用自己的邮箱或者Github、Google账号注册一个,注册完之后可能会直接由Dashboard跳转到Launchpad,这相当于已经为你创建一个Application了。因为Algolia搜索需要Index Name、Application ID和API Key,才能提供搜索。
2.创建索引,获取Key
你应该会在DashBoard的主页看到Application的App ID和API Key,或者点击上方的应用(Application)查看Application ID,也可以在主页点击“API Keys”查看API Key。
点击左侧的Search,进入到索引(Index)界面,创建一个新的索引,名字随意。(点击上方的Index,点击“Create Index”创建。)
创建好索引之后,点击Add records添加记录。如果想以JSON格式添加记录,点击Add manually,在新弹出的窗口中输入JSON信息,输入完成后,点击“save”添加记录,就像这样。
[
{
"title":"Hello World",
"link":"https://example.com/"
}
]
提交记录之后Index界面就会出现你添加的记录,上面会显示着各种attr的信息。
3.HTML+JS调用
保存好你的Application ID
、Search API Key
和Index Name
。新建一个html或者htm文件,编辑如下基本代码,成功之后可以根据喜好修改。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdn.jsdelivr.net/npm/algoliasearch@4.13.0/dist/algoliasearch-lite.umd.js"></script>
<script src="https://cdn.jsdelivr.net/npm/instantsearch.js@4.37.3/dist/instantsearch.production.min.js"></script>
</head>
<body>
<div id="search-box"></div> <!-- 搜索框容器 -->
<div id="hits"></div> <!-- 搜索结果容器 -->
<script>
const search = instantsearch({
indexName: '替换成你自己的Index Name',
searchClient: algoliasearch('替换成你自己的Application ID', '替换成你的Search API Key'),
});
search.addWidget(instantsearch.widgets.searchBox({ container: '#search-box' }));
search.addWidget(instantsearch.widgets.hits({ container: '#hits' }));
search.start();
</script>
</body>
</html>
这段代码运行之后,你的搜索应该能正常运行。但是数据有些杂乱,如果你需要展示特定的内容,可以在search.addWidget(instantsearch.widgets.searchBox({ container: '#search-box' }));
这段里面使用templates来自定义搜索结果模版。可以将那行代码改成:
//自定义搜索模版示例。可以将item里的内容改成你自己想要的样子。
search.addWidget(instantsearch.widgets.hits({ container: '#hits',templates:{empty:"没有找到搜索结果。",item: `<a href="{{link}}">{{#helpers.highlight}}{"attribute":"title"}{{/helpers.highlight}}</a>`}}));
成功之后,可以装饰你的搜索界面,然后测试。可以的话就挂在你自己的网站/博客上。