-------------
Windows phone 手机开发 、
ASP .NET培训、期待与您交流!----------------
最近学习了SQL Server中的一个新功能“全文本搜索”,这是在SQL Server 2005以后版本出现的新特性。全文本搜索一般用于大型数据的搜索,小型、中型数据一般很少会用到全文本搜索。数据库中还有个like关键字能够查找特殊值或部分行,虽然它对搜索机制非常有用,但是存在几个重要的问题。
1. 性能-----通配符匹配通常要求SQL Server尝试表中的所有行。因此,由于搜索行数不但的增加,这些搜索非常费时。
2.明确控制-----使用通配符匹配,很难控制匹配什么和不匹配什么。
3.智能化的结果-----虽然通配符的搜索提供了非常灵活的搜索,但是他们不能提供一种智能化的选择结果。
一、设置全文本搜索
1. 启动全文本搜索支持
输入:
exec sp_fulltext_database 'enable';
分析 :sp_fulltext_database是数据库自带的存储过程,接受一个指定启用(enable)还是禁用(disable)全文本搜索支持的参数
2.创建全文本目录
SQL Server在一个目录中存储存储过程。单个目录可用于多个表和索引,因此,可以使用一个现存的目录。如果没有现存的目录,则应该用Create fulltext catalog
创建一个目录
输入:
create fulltext catalog catalog_crashcourse;
分析:在默认的目录位置创建一个名位catalog_crashcourse的目录。为了指出具体的文件位置,可以用in path属性
3.创建全文本索引
输入:
create fulltext index on productnotes(note_text)key index pk_productnotes on catalog_crashcourse;
分析:在productnotes表上创建一个全文本索引,索引note_text列。需要唯一标识各行的键,因此用 key index 提供表的主键名为pk_productnotes。on子句指定用来存储全文本数据的目录,就是刚创建的全文本目录。
4.管理目录和索引
输入:
alter fulltext catalog catalog_crashcourse rebuild
分析: 删除和重建目录索引
二、进行全文本搜索
1.使用freetext进行搜索
输入:
select note_id,note_text
from productnotes
where note_text like '%rabit food%'
分析:使用like关键字在列note_text中查找短语rabit food。
输入:select note_id,note_text from productnotes where fulltext(note_text,'rabit food')
结果:
note_id note_text
104 Quantity varies,sold by the sack load.All guaranteed to be bright and orange,and suitable for use as rabbit bait
110 Customer complaint:rabbit has been able to detect trap,food apparently less effective now.
2.使用contains进行搜索
contains用来搜索包含词、短语、部分短语、具有相同词干的词,近视搜索、同义词等
输入:
select note_id ,note_text from productnotes where contains(note_text,'handsaw')
结果:
note_id note_text
112 Customer complaint:rabbit has been able to detect trap,food apparently less effe ctive now.
分析:功能上contains等同于like note_text='%handsaw%'。但是,contains搜索通常更快,特别市随着表的大小增加更是如此。
contains还支持使用通配符*,’“anvil*”‘表示匹配以anvil开始的单词。还支持布尔操作符and 、or和not,就不在一一说明了。
-------------
Windows phone 手机开发 、
ASP .NET培训、期待与您交流!----------------