0%

Mysql 与 Sqlite 的自然语言全文索引查询

问题

数据库里的值
123
456
789
想搜索的值是:abc123456
然后能匹配到数据库里的 123 或者 456,你们都是怎么做的?

解决

https://dev.mysql.com/doc/refman/8.0/en/fulltext-natural-language.html

建表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
mysql> CREATE TABLE articles (
id INT UNSIGNED AUTO_INCREMENT NOT NULL PRIMARY KEY,
title VARCHAR(200),
body TEXT,
FULLTEXT (title,body)
) ENGINE=InnoDB;

Query OK, 0 rows affected (0.08 sec)

mysql> INSERT INTO articles (title,body) VALUES
('MySQL Tutorial','DBMS stands for DataBase ...'),
('How To Use MySQL Well','After you went through a ...'),
('Optimizing MySQL','In this tutorial, we show ...'),
('1001 MySQL Tricks','1. Never run mysqld as root. 2. ...'),
('MySQL vs. YourSQL','In the following database comparison ...'),
('MySQL Security','When configured properly, MySQL ...');

Query OK, 6 rows affected (0.01 sec)
Records: 6 Duplicates: 0 Warnings: 0

SELECT * FROM articles
WHERE MATCH (title,body)
AGAINST ('database' IN NATURAL LANGUAGE MODE);
+----+-------------------+------------------------------------------+
| id | title | body |
+----+-------------------+------------------------------------------+
| 1 | MySQL Tutorial | DBMS stands for DataBase ... |
| 5 | MySQL vs. YourSQL | In the following database comparison ... |
+----+-------------------+------------------------------------------+
2 rows in set (0.00 sec)

查询

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
SELECT id, body, MATCH (title,body)
AGAINST ('Security implications of running MySQL as root'
IN NATURAL LANGUAGE MODE) AS score
FROM articles
WHERE MATCH (title,body)
AGAINST('Security implications of running MySQL as root'
IN NATURAL LANGUAGE MODE);

+----+-------------------------------------+-----------------+
| id | body | score |
+----+-------------------------------------+-----------------+
| 4 | 1. Never run mysqld as root. 2. ... | 1.5219271183014 |
| 6 | When configured properly, MySQL ... | 1.3114095926285 |
+----+-------------------------------------+-----------------+
2 rows in set (0.00 sec)

Sqlite 也有,但是要切片查询。