diff --git a/部署PostGIS.md b/部署PostGIS.md index 88e1875..b83c25a 100644 --- a/部署PostGIS.md +++ b/部署PostGIS.md @@ -138,28 +138,37 @@ SELECT to_tsvector('chinese_mix', 'Hello world, 你好世界,PostgreSQL 很棒 ## 测试 ```sql --- 创建测试表 CREATE TABLE articles ( id SERIAL PRIMARY KEY, title TEXT, - content TEXT + content TEXT, + -- 生成列:自动维护 tsvector,避免每次查询都计算,提高性能 + content_tsvector TSVECTOR GENERATED ALWAYS AS (to_tsvector('chinese_mix', content)) STORED ); --- 插入测试数据 (中英混合) +-- 插入一些混合数据 INSERT INTO articles (title, content) VALUES -('Introduction to AI', 'Artificial Intelligence is changing the world.'), -('人工智能简介', '人工智能正在改变世界,PostgreSQL 是很好的存储工具。'), -('PG 16 New Features', 'PostgreSQL 16 brings better performance and json features.'); +('AI 技术展望', '人工智能 (AI) 正在改变世界,PostgreSQL 是存储这些数据的首选数据库。'), +('PostgreSQL 16 新特性', 'PostgreSQL 16 带来了更好的性能,支持 JSON 增强和中文分词优化。'), +('日常开发笔记', 'Today I learned about zhparser. 它让中文搜索变得很简单。'); --- 创建 GIN 索引 (加速检索的关键) -CREATE INDEX idx_articles_content ON articles USING GIN (to_tsvector('chinese_mix', content)); +-- 搜索包含 "人工智能" 的文章 +SELECT title, content +FROM articles +WHERE content_tsvector @@ to_tsquery('chinese_mix', '人工智能'); --- 搜索 "人工智能" -SELECT title FROM articles WHERE to_tsvector('chinese_mix', content) @@ to_tsquery('chinese_mix', '人工智能'); +-- 搜索包含 "PostgreSQL" 的文章 +SELECT title, content +FROM articles +WHERE content_tsvector @@ to_tsquery('chinese_mix', 'PostgreSQL'); --- 搜索 "PostgreSQL" (英文) -SELECT title FROM articles WHERE to_tsvector('chinese_mix', content) @@ to_tsquery('chinese_mix', 'PostgreSQL'); +-- 搜索既包含 "数据库" 又包含 "PostgreSQL" 的文章 +SELECT title, content +FROM articles +WHERE content_tsvector @@ to_tsquery('chinese_mix', '数据库 & PostgreSQL'); --- 搜索混合条件 -SELECT title FROM articles WHERE to_tsvector('chinese_mix', content) @@ to_tsquery('chinese_mix', '数据库 & 改变'); +-- 搜索包含 "AI" 或者 "改变" 的文章 +SELECT title, content +FROM articles +WHERE content_tsvector @@ to_tsquery('chinese_mix', 'AI | 改变'); ``` \ No newline at end of file