MySQL基本操作(三):全文本搜索

1、MyISAM支持全文本搜索,而InnoDB不支持。因此要在创建表的时候,加上engine=MyISAM;

2、一般在创建表时启用全文本搜索。在定义之后,MySQL自动维护该索引。在增加、更新或删除行时,索引随之自动更新。

3、不要在导入数据时使用FULLTEXT

4、建表并导入数据

(1)建表如图
MySQL基本操作(三):全文本搜索_第1张图片

(2)导入数据如图
MySQL基本操作(三):全文本搜索_第2张图片

(3)代码如下

#!/usr/bin/python
# encoding: utf-8
import MySQLdb
# 打开数据库连接
conn = MySQLdb.connect(host="localhost", user="root", passwd="111111", db="ltz")
# 使用cursor()方法获取操作游标
cursor = conn.cursor()
# 如果数据表已经存在使用 execute() 方法删除表。
cursor.execute("DROP TABLE IF EXISTS productnotes")

#1. 创建数据表SQL语句
sql = """CREATE TABLE productnotes(
         note_id int not null auto_increment,  
         note_text text null,  
         primary key(note_id),  
         fulltext(note_text))engine=MyISAM;""" #使用fulltext()&&engine=MyISAM!
cursor.execute(sql)

#2. SQL 一次插入多条记录!!!!!!!
sql = """INSERT INTO productnotes(
         note_id,
         note_text)
         VALUES ('1', "LimsLink is designed to interface output from
chromatography data systems (CDSs) to LIMS."),
                ('2', "This line of proprietary reagents, 
containers, and automation tools is designed for genomics and drug discovery research."),
                ('3', "line  reagents, containers, tools is designed 
for genomics and drug discovery research."),
                ('4', "specificities include both alpha–beta and 
beta–beta. This line from chromatography .data systems (CDSs) and toLIMS.");"""
try:
   # 执行sql语句
   cursor.execute(sql)
   # 提交到数据库执行
   conn.commit()
except:
   # Rollback in case there is any error
   conn.rollback()

conn.close()

6、进行全文本搜索

进行全文本搜索,必须索引被搜索的列,而且要随着数据的改变不断地重新索引。在对表列进行适当设计后,MySQL会自动进行所有的索引和重新索引。
在索引之后,SELECT可与Match()和Against()一起使用以实际执行搜索。

(1)布尔文本搜索(boolean mode)

/* 匹配designed*/
MySQL基本操作(三):全文本搜索_第3张图片

/* 匹配This或匹配systems */
MySQL基本操作(三):全文本搜索_第4张图片

或者
MySQL基本操作(三):全文本搜索_第5张图片

其他搜索方法有待完善。

你可能感兴趣的:(数据库)