Implement 完整-文本搜索在 SQL
完整-文本搜索 indexes words 在文本为 快 searching. Learn 到 use FULLTEXT indexes, tsvector, 和 ranking.
- 1
完整-文本搜索 tokenizes 文本为 words, stems 它们, 和 indexes 为快 lookup. MySQL: FULLTEXT 索引 + 匹配() 针对(). PostgreSQL: tsvector + tsquery + GIN 索引. SQLite: FTS5 virtual 表. Features: 字 matching, phrase matching, ranking (relevance 评分), stemming, 停止 words, synonyms.
- 2 SQL 格式化器 →
格式化 full-text search queries. MySQL: SELECT * FROM articles WHERE MATCH(title, body) AGAINST('database' IN NATURAL LANGUAGE MODE). PostgreSQL: SELECT * FROM articles WHERE to_tsvector(body) @@ to_tsquery('database'). Format makes the search expression clear.
- 3 正则表达式测试器 →
为简单文本搜索无 完整-文本 indexes, use LIKE 或 regex. LIKE '%字%' 是慢 (否索引) 但工作处处. Regex 是更多 powerful 但 also 慢. 为 production 搜索, use 完整-文本 indexes 或 dedicated 搜索 engine (Elasticsearch, Meilisearch).
常见问题
- 完整-文本搜索 vs LIKE?
- LIKE '%字%' scans 每个行 (否索引) — 慢开 大 tables. 完整-文本搜索我们 inverted 索引 — 快, supports ranking, stemming, 和 phrase matching. Use LIKE 为简单 substring matching 开小 tables; use 完整-文本搜索为 searching 文本内容开 大 tables.
- 应该 I use SQL 完整-文本或 Elasticsearch?
- 为简单搜索内 one 数据库, SQL 完整-文本是 充分和 simpler. 为复杂搜索 (faceted, fuzzy, multi-entity, relevance tuning), use Elasticsearch 或 Meilisearch. 权衡: SQL 是 simpler 但 limited; 搜索 engines 是 powerful 但添加 infrastructure complexity.