


Let's talk about how MySQL full-text index solves the problem of slow like fuzzy matching queries
Fuzzy query, such as querying users whose names contain "xiao", the common way of writing is like "%xiao%". In MySQL, it will scan the entire table, so the amount of data is small, which is fine. Full table scan is also very fast, but will become slower as the data increases, and it is very heavy to load ES. This article will introduce to you the solution to slow like fuzzy matching queries - MySQL full-text index.
Requirements
Need fuzzy matching to query a word
select * from t_phrase where LOCATE('Chan',phrase) = 0;
select * from t_chinese_phrase where instr(phrase,'Chan') > 0;
select * from t_chinese_phrase where phrase like '%长%'
Explain and take a look at the execution plan
It can be seen from the results of explain that although we build phrase The index is set, but when querying, the index is invalid.
reason: The index of mysql is a B-tree structure. InnoDB's use of "%xx" when fuzzy querying data will cause the index to fail (I will not go into details here)
From the perspective of query time, the time spent: 90ms
Current data volume: 93230 (9.3W) already requires 90ms. This time is not acceptable. If the data volume increases, this time will continue to grow.
Solution:
When the amount of data is not large, use the full-text index of mysql;
When the amount of data is relatively large or the full-text index of mysql does not meet expectations , you can consider using ES
The following is mainly related to the full-text index of MySQL.
Full-text index introduction
1. Development History
The full-text index of the old version of MySQL can only be used on the char, varchar and text fields of the MyISAM storage engine.
The InnoDB engine on MySQL5.6.24 has also added full-text indexing.
2. Full-text index
- #Full-Text Search is stored in the database Technology to find information from any content in the entire book or entire article. It can obtain information about chapters, sections, paragraphs, words, etc. in the full text as needed, and can also perform various statistics and analysis
3. Create a full-text index
If you need to set up a full-text index for a large amount of data, it is recommended to add the data first and then create the index.
1. Create a full-text index when creating a table
create table 表名( 字段名1, 字段名2, 字段名3, 字段名4, FULLTEXT full_index_name (字段名) )ENGINE=InnoDB;
2. Add a full-text index to an existing table
create fulltext index index name on table name (field name );
eg:
create table t_word ( id int unsigned auto_increment comment '自增id' primary key, uid char(32) not null comment '32位唯一id', word varchar(256) null comment '英文单词', translate varchar(256) null ); create fulltext index full_idx_translate on t_word (translate); create fulltext index full_idx_word on t_word (word); INSERT INTO t_word (id, uid, word, translate) VALUES (1, '9d592499c65648b0a9519206688ef3f9', 'lion', '狮子'); INSERT INTO t_word (id, uid, word, translate) VALUES (2, 'ce26ac4239514bc6af481bcb1d9b67df', 'panda', '熊猫'); INSERT INTO t_word (id, uid, word, translate) VALUES (3, 'a7d6042853c44904b68275daafb44702', 'tiger', '老虎'); INSERT INTO t_word (id, uid, word, translate) VALUES (4, 'f13bd0a8ecea44fc9ade1625eeb4cc3c', 'goat', '山羊'); INSERT INTO t_word (id, uid, word, translate) VALUES (5, '27d5cbfc93a046388d712085e567474f', 'sheep', '绵羊'); INSERT INTO t_word (id, uid, word, translate) VALUES (6, 'ed35df138cf348aa937781be8ee21cbf', 'lamb', '羊羔'); INSERT INTO t_word (id, uid, word, translate) VALUES (7, 'fba5861d9527440990276e999f47ef8f', 'buffalo', '水牛'); INSERT INTO t_word (id, uid, word, translate) VALUES (8, '3a72e76f210841b1939fff0d3d721375', 'bull', '公牛'); INSERT INTO t_word (id, uid, word, translate) VALUES (9, '272e0b28ea7a48248a86f17533bf9943', 'cow', '母牛'); INSERT INTO t_word (id, uid, word, translate) VALUES (10, '47127adface54e418e4c1b9980af6d16', 'calf', '小牛'); INSERT INTO t_word (id, uid, word, translate) VALUES (11, '10592499c65648b0a9519206688ef3f9', 'little lion', '小狮子'); INSERT INTO t_word (id, uid, word, translate) VALUES (12, '1bf095110b634a01bee5b31c5ee7ee0c', 'little cow', '母牛'); INSERT INTO t_word (id, uid, word, translate) VALUES (13, '4813e588cde54c30bd65bfdbb243ad1f', 'little calf', '小小牛'); INSERT INTO t_word (id, uid, word, translate) VALUES (14, '5e377e281ad344048b6938a638b78ccb', 'little bull', '小公牛'); INSERT INTO t_word (id, uid, word, translate) VALUES (15, '2855ad0da2964c7682c178eb8271f13d', 'little buffalo', '小水牛'); INSERT INTO t_word (id, uid, word, translate) VALUES (16, '72f24c9a77644d57a36f3bdf2b8116b0', 'little lamb', '小羊羔'); INSERT INTO t_word (id, uid, word, translate) VALUES (17, '2d592499c65648b0a9519206688ef3f9', 'I''m a big lion', '我是一只大狮子');
3. Delete the full-text index
alter table table name drop index index name;
4. Full-text index uses
syntax
MATCH(col1,col2,...) AGAINST(expr[search_modifier]) search_modifier: { IN NATURAL LANGUAGE MODE | IN NATURAL LANGUAGE MODE WITH QUERY EXPANSION | IN BOOLEAN MODE | WITH QUERY EXPANSION }
4.1 IN NATURAL LANGUAGE MODE
The natural language mode is MySQL default Full-text search mode for . Natural language mode cannot use operators, and cannot specify complex queries such as keywords that must appear or must not appear.
// 默认是使用 in natural language mode select * from t_word where match(word) against ('lion'); // 或者 显示写 select * from t_word where match(word) against ('lion' in natural language mode);
The results are as follows:
4.2 IN BOOLEAN MODE
BOOLEAN modeYou can use operators , can support complex queries such as specifying whether keywords must appear or must not appear, or whether the weight of keywords is high or low. Recommended to use boolean mode
Description | |
---|---|
Default, contains the word | |
Includes, this word must exist. | |
Exclusion, the word must not appear. | |
Include and increase the ranking value, the query results will be higher | ##< ; |
() | |
~ | |
* | |
"" | |
The above is the detailed content of Let's talk about how MySQL full-text index solves the problem of slow like fuzzy matching queries. For more information, please follow other related articles on the PHP Chinese website!

MySQL'sBLOBissuitableforstoringbinarydatawithinarelationaldatabase,whileNoSQLoptionslikeMongoDB,Redis,andCassandraofferflexible,scalablesolutionsforunstructureddata.BLOBissimplerbutcanslowdownperformancewithlargedata;NoSQLprovidesbetterscalabilityand

ToaddauserinMySQL,use:CREATEUSER'username'@'host'IDENTIFIEDBY'password';Here'showtodoitsecurely:1)Choosethehostcarefullytocontrolaccess.2)SetresourcelimitswithoptionslikeMAX_QUERIES_PER_HOUR.3)Usestrong,uniquepasswords.4)EnforceSSL/TLSconnectionswith

ToavoidcommonmistakeswithstringdatatypesinMySQL,understandstringtypenuances,choosetherighttype,andmanageencodingandcollationsettingseffectively.1)UseCHARforfixed-lengthstrings,VARCHARforvariable-length,andTEXT/BLOBforlargerdata.2)Setcorrectcharacters

MySQloffersechar, Varchar, text, Anddenumforstringdata.usecharforfixed-Lengthstrings, VarcharerForvariable-Length, text forlarger text, AndenumforenforcingdataAntegritywithaetofvalues.

Optimizing MySQLBLOB requests can be done through the following strategies: 1. Reduce the frequency of BLOB query, use independent requests or delay loading; 2. Select the appropriate BLOB type (such as TINYBLOB); 3. Separate the BLOB data into separate tables; 4. Compress the BLOB data at the application layer; 5. Index the BLOB metadata. These methods can effectively improve performance by combining monitoring, caching and data sharding in actual applications.

Mastering the method of adding MySQL users is crucial for database administrators and developers because it ensures the security and access control of the database. 1) Create a new user using the CREATEUSER command, 2) Assign permissions through the GRANT command, 3) Use FLUSHPRIVILEGES to ensure permissions take effect, 4) Regularly audit and clean user accounts to maintain performance and security.

ChooseCHARforfixed-lengthdata,VARCHARforvariable-lengthdata,andTEXTforlargetextfields.1)CHARisefficientforconsistent-lengthdatalikecodes.2)VARCHARsuitsvariable-lengthdatalikenames,balancingflexibilityandperformance.3)TEXTisidealforlargetextslikeartic

Best practices for handling string data types and indexes in MySQL include: 1) Selecting the appropriate string type, such as CHAR for fixed length, VARCHAR for variable length, and TEXT for large text; 2) Be cautious in indexing, avoid over-indexing, and create indexes for common queries; 3) Use prefix indexes and full-text indexes to optimize long string searches; 4) Regularly monitor and optimize indexes to keep indexes small and efficient. Through these methods, we can balance read and write performance and improve database efficiency.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version
Chinese version, very easy to use

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version
Visual web development tools
