返回博客

MySQL 与 SQLite 的自然语言全文索引查询

如何在 MySQL 和 SQLite 数据库中使用自然语言模式进行全文索引查询,并匹配包含部分关键词的记录,例如搜索 "abc123456" 匹配到包含 "123" 或 "456" 的记录。文章详细介绍了 MySQL 的 FULLTEXT 索引和查询方法,以及 SQLite 的分片查询策略。

Mt.r
|

问题

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

解决

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

建表

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)

查询

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 也有,但是要切片查询。