搜索功能实现

实现全文搜索功能

提示词

请为[数据类型]实现搜索功能:

需求:
- 搜索字段:[标题、内容、标签等]
- 搜索方式:[模糊匹配/全文搜索/拼音搜索]
- 数据量:[如10万条]
- 要求:实时搜索(防抖)、高亮、相关度排序

方案建议:
1. 简单方案:LIKE查询(小数据量)
2. 中等方案:全文索引
3. 高级方案:Elasticsearch/Meilisearch

给出推荐方案的完整实现。

示例输出

推荐:Meilisearch(轻量、快速、开箱即用)

后端:

import { MeiliSearch } from 'meilisearch';
const client = new MeiliSearch({ host: 'http://localhost:7700' });
const index = client.index('articles');

// 搜索API
app.get('/api/search', async (req, res) => {
  const { q, page = 1 } = req.query;
  const results = await index.search(q, {
    limit: 20,
    offset: (page - 1) * 20,
    attributesToHighlight: ['title', 'content'],
  });
  res.json(results);
});

前端(防抖搜索):

const debouncedSearch = useMemo(
  () => debounce(async (query) => {
    setLoading(true);
    const res = await fetch(`/api/search?q=${query}`);
    setResults(await res.json());
    setLoading(false);
  }, 300),
  []
);
0

评论 0

更多

登录后可点赞、收藏、评论和举报。

还没有评论,先发起一个具体问题。