Typesense 开源搜索引擎教程
项目介绍
Typesense 是一个现代、快速、开源的搜索引擎,旨在为开发者提供一个易于使用的搜索解决方案。它是一个开源的 Algolia 和 Pinecone 的替代品,也是一个比 Elasticsearch 更易于使用的替代品。Typesense 使用最新的算法,充分利用了硬件能力和机器学习的最新进展,提供了即搜即得、自动完成、分面导航、地理搜索、模糊搜索、向量搜索和语义搜索等功能。
项目快速启动
环境准备
在开始之前,请确保您的系统满足以下依赖要求:
- C++11 兼容的编译器(GCC >= 4.9.0, Apple Clang >= 8.0, Clang >= 3.9.0)
- Snappy
- zlib
- OpenSSL (>=1.0.2)
- curl
- ICU
构建 Typesense
-
克隆项目仓库:
git clone https://github.com/typesense/typesense.git cd typesense -
安装依赖:
sudo apt-get install -y build-essential snappy zlib1g-dev libssl-dev libcurl4-openssl-dev libicu-dev -
使用 Bazel 构建 Typesense:
bazel build //:typesense-server
启动 Typesense 服务器
构建完成后,您可以启动 Typesense 服务器: bash ./bazel-bin/typesense-server --data-dir=/path/to/data --api-key=your_api_key
应用案例和最佳实践
案例一:xkcd 漫画搜索
Typesense 可以用于构建一个按主题浏览 xkcd 漫画的应用。以下是一个简单的示例:
const Typesense = require('typesense');
const client = new Typesense.Client({
nodes: [{
host: 'localhost',
port: '8108',
protocol: 'http'
}],
apiKey: 'your_api_key',
connectionTimeoutSeconds: 2
});
const schema = {
name: 'comics',
fields: [
{ name: 'title', type: 'string' },
{ name: 'transcript', type: 'string' },
{ name: 'num', type: 'int32' }
]
};
client.collections().create(schema).then(() => {
console.log('Collection created');
});
案例二:电子商务商店前端
使用 Typesense 和 Next.js 构建一个电子商务商店前端,提供快速且耐错的搜索体验。
import TypesenseInstantSearchAdapter from 'typesense-instantsearch-adapter';
const typesenseInstantsearchAdapter = new TypesenseInstantSearchAdapter({
server: {
apiKey: 'your_api_key',
nodes: [
{
host: 'localhost',
port: '8108',
protocol: 'http'
}
]
},
additionalSearchParameters: {
queryBy: 'title,description'
}
});
const searchClient = typesenseInstantsearchAdapter.searchClient;
const search = instantsearch({
indexName: 'products',
searchClient
});
search.addWidgets([
instantsearch.widgets.searchBox({
container: '#searchbox'
}),
instantsearch.widgets.hits({
container: '#hits',
templates: {
item: `
<div>
<strong>{{#helpers.highlight}}{ "attribute": "title" }{{/helpers.highlight}}</strong>
<p>{{#helpers.highlight}}{ "attribute": "description" }{{/helpers.highlight}}</p>
</div>
`
}
})
]);
search.start();
典型生态项目
Typesense Python 客户端
Typesense 提供了官方的 Python 客户端,方便 Python 开发者与 Typesense 服务器进行交互。
from typesense import Client
client = Client({
'nodes': [{
'host': 'localhost',
'port': '8108',
'protocol': 'http'
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考



