SQL Server 的全文檢索功能能夠對大量文字資料進行高效的語意搜尋,超越傳統 LIKE 查詢的效能限制。本文透過 pubs 範例資料庫,完整示範從啟用全文索引到實際查詢的完整流程。
use pubs
go
execute sp_fulltext_database 'enable'
go
execute sp_fulltext_catalog 'ft_titles', 'create'
go
全文目錄是儲存全文索引的邏輯容器,一個資料庫可建立多個目錄以利管理。
execute sp_fulltext_table 'titles', 'create', 'ft_titles', 'UPKCL_titleidind'
go
參數說明:
titles:目標資料表ft_titles:所屬全文目錄UPKCL_titleidind:資料表的唯一索引(主鍵索引),可透過 sp_help titles 查詢取得exec sp_fulltext_column 'titles', 'title', 'add'
go
exec sp_fulltext_column 'titles', 'notes', 'add'
go
exec sp_fulltext_table 'titles', 'activate'
go
exec sp_fulltext_catalog 'ft_titles', 'start_full'
go
-- 片語搜尋
select title, notes from titles
where contains(title, '"computer Cooking"')
go
-- 單一關鍵字
select title, notes from titles
where contains(title, 'computer')
go
-- 自然語言查詢
select title, notes from titles
where freetext(title, 'computer Cooking')
go
select title, notes from titles
where freetext(title, '"computer Cooking"')
go
-- 搜尋所有全文索引欄位
select title, notes from titles
where freetext(*, 'computer')
go
| 特性 | CONTAINS | FREETEXT |
|---|---|---|
| 搜尋模式 | 精確匹配、支援布林邏輯、近接搜尋 | 語意擴展、詞幹分析、同義詞匹配 |
| 適用場景 | 精確查找特定詞彙或片語 | 自然語言問答、模糊概念搜尋 |
| 效能 | 較快 | 較慢(需語意分析) |
start_incremental 或 start_full 更新索引