From time to time I see pattern matching queries with conditions that look like this: “where fieldname like ‘%something%’ “. MySQL cannot use indexes for these kinds of queries, which means it has to do a table scan every single time.
(That’s really only half true — there are the FullText indexes. In another blog post I will cover FullText indexes as well.)
I recently was trying to find a solution, and my friend Charles Nagy reminded me of Trigrams. Let me show you the Trigram of the name Daniel:
|
1 |
daniel:<br>dan<br>ani<br>nie<br>iel<br> |
Let me show you an example. You have the following email schema:
|
1 |
CREATE TABLE `email` (<br> `id` int(10) unsigned NOT NULL AUTO_INCREMENT,<br> `email` varchar(120) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',<br> PRIMARY KEY (`id`),<br> KEY `idx_email` (`email`)<br>) ENGINE=InnoDB AUTO_INCREMENT=318459 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci |
With data like these:
|
1 |
+--------+-------------------------------+<br>| id | email |<br>+--------+-------------------------------+<br>| 8392 | ehintz@example.com |<br>| 238396 | williamson.pierre@example.net |<br>| 286517 | godfrey79@example.org |<br>| 137291 | welch.durward@example.org |<br>| 291984 | curtis67@example.net |<br>...<br>+--------+-------------------------------+ |
And we are looking for email addresses like ‘%n.pierre%’:
|
1 |
mysql> select * from email where email like '%n.pierre%';<br>+--------+-------------------------------+<br>| id | email |<br>+--------+-------------------------------+<br>| 90587 | anderson.pierre@example.org |<br>| 133352 | friesen.pierre@example.net |<br>| 118937 | green.pierre@example.net |<br>| 118579 | hudson.pierre@example.com |<br>| 237928 | johnson.pierre@example.org |<br>| 59526 | larkin.pierre@example.net |<br>| 278384 | monahan.pierre@example.net |<br>| 58625 | olson.pierre@example.org |<br>| 306718 | rohan.pierre@example.com |<br>| 200608 | wilkinson.pierre@example.org |<br>| 238396 | williamson.pierre@example.net |<br>+--------+-------------------------------+<br>11 rows in set (0.12 sec)<br><br>mysql> explain select * from email where email like '%n.pierre%'G<br>*************************** 1. row ***************************<br> id: 1<br> select_type: SIMPLE<br> table: email<br> partitions: NULL<br> type: index<br>possible_keys: NULL<br> key: idx_email<br> key_len: 362<br> ref: NULL<br> rows: 332475<br> filtered: 11.11<br> Extra: Using where; Using index<br>1 row in set, 1 warning (0.00 sec)<br><br>mysql> show session status like '%handler%';<br>+----------------------------+--------+<br>| Variable_name | Value |<br>+----------------------------+--------+<br>| Handler_commit | 1 |<br>| Handler_delete | 0 |<br>| Handler_discover | 0 |<br>| Handler_external_lock | 2 |<br>| Handler_mrr_init | 0 |<br>| Handler_prepare | 0 |<br>| Handler_read_first | 1 |<br>| Handler_read_key | 1 |<br>| Handler_read_last | 0 |<br>| Handler_read_next | 318458 |<br>| Handler_read_prev | 0 |<br>| Handler_read_rnd | 0 |<br>| Handler_read_rnd_next | 0 |<br>| Handler_rollback | 0 |<br>| Handler_savepoint | 0 |<br>| Handler_savepoint_rollback | 0 |<br>| Handler_update | 0 |<br>| Handler_write | 0 |<br>+----------------------------+--------+<br>18 rows in set (0.00 sec) |
There are 11 email addresses, but it has to scan the whole index (318458 rows). That’s not good! Let’s try and make it better.
I created a table like this:
|
1 |
CREATE TABLE `email_trigram` (<br> `id` int(10) unsigned NOT NULL AUTO_INCREMENT,<br> `email_id` int(10) unsigned NOT NULL,<br> `trigram` char(3) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',<br> PRIMARY KEY (`id`),<br> KEY `idx_email_id` (`email_id`),<br> KEY `idx_trigram` (`trigram`)<br>) ENGINE=InnoDB AUTO_INCREMENT=2749001 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci |
As we can see, there is an index called “trigram“.
The plan is to create a trigram for every single email addresses. I wrote the following trigger:
|
1 |
create trigger insert_trigram after insert ON test.email FOR EACH ROW <br>BEGIN<br><br>DECLARE email_length int;<br>declare x int ;<br>declare i int ;<br>SELECT CHAR_LENGTH(SUBSTRING_INDEX(email,'@',1)) into email_length from test.email where email=NEW.email and id=NEW.id;<br><br>set i=1;<br>set x=3;<br> while email_length >= 3 do<br><br> INSERT INTO email_trigram (email_id,trigram) values (NEW.id,substring(NEW.email from i for x));<br> set email_length=email_length-1;<br> set i=i+1;<br> end while ;<br><br>END |
When there is an insert, it creates and inserts the trigrams into the email_trigram table. Trigrams for anderson.pierre:
|
1 |
mysql> select trigram from email_trigram where email_id=90587;<br>+---------+<br>| trigram |<br>+---------+<br>| and |<br>| nde |<br>| der |<br>| ers |<br>| rso |<br>| son |<br>| on. |<br>| n.p |<br>| .pi |<br>| pie |<br>| ier |<br>| err |<br>| rre |<br>+---------+ |
With the following query, we can find all the email addresses with n.pierre:
|
1 |
SELECT e.email<br>FROM email AS e<br>INNER JOIN<br>( SELECT tr.email_id<br>FROM email_trigram AS tr<br>WHERE tr.trigram IN ("n.p",".pi","pie","ier","err","rre")<br>GROUP BY tr.email_id HAVING count(*) =6) AS ti ON ti.email_id=e.id;<br><br>*************************** 1. row ***************************<br> id: 1<br> select_type: PRIMARY<br> table: <derived2><br> partitions: NULL<br> type: ALL<br>possible_keys: NULL<br> key: NULL<br> key_len: NULL<br> ref: NULL<br> rows: 8214<br> filtered: 100.00<br> Extra: NULL<br>*************************** 2. row ***************************<br> id: 1<br> select_type: PRIMARY<br> table: e<br> partitions: NULL<br> type: eq_ref<br>possible_keys: PRIMARY<br> key: PRIMARY<br> key_len: 4<br> ref: ti.email_id<br> rows: 1<br> filtered: 100.00<br> Extra: NULL<br>*************************** 3. row ***************************<br> id: 2<br> select_type: DERIVED<br> table: tr<br> partitions: NULL<br> type: range<br>possible_keys: idx_email_id,idx_trigram<br> key: idx_trigram<br> key_len: 9<br> ref: NULL<br> rows: 8214<br> filtered: 100.00<br> Extra: Using index condition; Using temporary; Using filesort<br>3 rows in set, 1 warning (0.00 sec) |
It does not have to read the whole table, but still needs to read a lot of rows and even using filesort. I did not want to create trigrams manually, so I wrote the following procedure:
|
1 |
create procedure select_email(IN email_address varchar(255))<br>begin<br><br>DECLARE email_length int;<br>declare x int ;<br>declare i int ;<br>declare trigram varchar(255) ;<br>declare trigram_list varchar(255) ;<br><br>SELECT CHAR_LENGTH(SUBSTRING_INDEX(email_address,'@',1)) into email_length;<br><br>set i=1;<br>set x=3;<br> while email_length >= 3 do<br><br> select substring(SUBSTRING_INDEX(email_address,'@',1) from i for x) into trigram;<br> set trigram_list=concat_ws('","',trigram_list,trigram);<br><br> set email_length=email_length-1;<br> set i=i+1;<br> end while ;<br><br>set trigram_list=concat('"',trigram_list,'"');<br><br>set @final= concat( " SELECT e.email<br>FROM email AS e<br>INNER JOIN<br>( SELECT tr.email_id<br> FROM email_trigram AS tr<br> WHERE tr.trigram IN (" , trigram_list , ")<br> GROUP BY tr.email_id HAVING count(*) =" , i-1 , ") AS ti ON ti.email_id=e.id" );<br><br>PREPARE stmt FROM @final;<br>EXECUTE stmt;<br>DEALLOCATE PREPARE stmt;<br><br>end |
Since with trigrams we are looking for parts of the words (like err or ier), there can be many matches. If we are using a longer condition like derson.pierre, the procedure needed to read 65722 rows. This is also a lot.
Let’s have a look at the selectivity a bit:
|
1 |
mysql> select trigram,count(*) as c from email_trigram group by trigram order by c desc limit 10;<br>+---------+-------+<br>| trigram | c |<br>+---------+-------+<br>| er. | 12919 |<br>| ann | 12726 |<br>| man | 12462 |<br>| ell | 12257 |<br>| ber | 12225 |<br>| sch | 11753 |<br>| son | 10983 |<br>| ill | 9443 |<br>| mar | 9294 |<br>| ert | 8839 |<br>+---------+-------+<br>10 rows in set (1.59 sec) |
There are parts that give back many rows. As I mentioned, more parts mean more rows.
I was hoping for a bigger improvement, so I wondered what else we could do. MySQL cannot use an index because of the leading %. How can we avoid that? Let’s save all the possible versions of the email address that we could be looking for.
(I don’t know if there is any official name of this method — if someone knows it, please write a comment.)
|
1 |
anderson.pierre@example.org:<br>anderson.pierre<br>nderson.pierre<br>derson.pierre<br>erson.pierre<br>rson.pierre<br>son.pierre<br>on.pierre<br>n.pierre<br>.pierre<br>pierre<br>ierre<br>erre<br>rre |
Hmm.. could this work? Let’s test it. I created the following table and trigger:
|
1 |
CREATE TABLE `email_tib` (<br> `id` int(10) unsigned NOT NULL AUTO_INCREMENT,<br> `email_id` int(10) unsigned NOT NULL,<br> `email_parts` varchar(120) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',<br> PRIMARY KEY (`id`),<br> KEY `idx_email_id` (`email_id`),<br> KEY `idx_trigram` (`email_parts`)<br>) ENGINE=InnoDB AUTO_INCREMENT=2749001 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci<br><br>create trigger insert_tib after insert ON test.email FOR EACH ROW <br>BEGIN<br><br>DECLARE email_length int;<br>declare x int ;<br>declare i int ;<br>SELECT CHAR_LENGTH(SUBSTRING_INDEX(email,'@',1)) into email_length from test.email where email=NEW.email and id=NEW.id;<br><br>set i=-3;<br> while email_length >= 3 do<br><br> INSERT INTO email_tib (email_id,email_parts) values (NEW.id,substring((SUBSTRING_INDEX(NEW.email,'@',1)),i));<br> set email_length=email_length-1;<br> set i=i-1;<br> end while ;<br><br>END |
Let’s find the email addresses that contain n.pierre:
|
1 |
mysql> SELECT e.email<br>FROM email AS e<br>RIGHT JOIN email_tib AS t ON t.email_id=e.id<br>WHERE t.email_parts LIKE "n.pierre%";<br>+-------------------------------+<br>| email |<br>+-------------------------------+<br>| anderson.pierre@example.org |<br>| friesen.pierre@example.net |<br>| green.pierre@example.net |<br>| hudson.pierre@example.com |<br>| johnson.pierre@example.org |<br>| larkin.pierre@example.net |<br>| monahan.pierre@example.net |<br>| olson.pierre@example.org |<br>| rohan.pierre@example.com |<br>| wilkinson.pierre@example.org |<br>| williamson.pierre@example.net |<br>+-------------------------------+<br>11 rows in set (0.00 sec)<br><br>mysql> show session status like '%handler%';<br>+----------------------------+-------+<br>| Variable_name | Value |<br>+----------------------------+-------+<br>| Handler_commit | 1 |<br>| Handler_delete | 0 |<br>| Handler_discover | 0 |<br>| Handler_external_lock | 4 |<br>| Handler_mrr_init | 0 |<br>| Handler_prepare | 0 |<br>| Handler_read_first | 0 |<br>| Handler_read_key | 12 |<br>| Handler_read_last | 0 |<br>| Handler_read_next | 11 |<br>| Handler_read_prev | 0 |<br>| Handler_read_rnd | 0 |<br>| Handler_read_rnd_next | 0 |<br>| Handler_rollback | 0 |<br>| Handler_savepoint | 0 |<br>| Handler_savepoint_rollback | 0 |<br>| Handler_update | 0 |<br>| Handler_write | 0 |<br>+----------------------------+-------+<br>18 rows in set (0.00 sec) |
Wow, that is much better than the previous one! It is more than 100 times faster! Now you can have a beer because you deserve it. 🙂
|
1 |
mysql> select email_parts,count(*) as c <br>from email_tib group by email_parts <br>order by c desc limit 10;<br>+-------------+------+<br>| email_parts | c |<br>+-------------+------+<br>| son | 6228 |<br>| ler | 3863 |<br>| ner | 3635 |<br>| ann | 3590 |<br>| mann | 3464 |<br>| man | 3387 |<br>| ski | 3331 |<br>| ton | 2659 |<br>| ell | 2482 |<br>| ger | 2437 |<br>+-------------+------+<br>10 rows in set (1.61 sec) |
There are parts that result in many readings as well, but it helps a lot now that we are using a longer pattern:
|
1 |
mysql> select email_parts,count(*) as c <br>from email_tib where length(email_parts) > 5 <br>group by email_parts order by c desc limit 10;<br>+-------------+-----+<br>| email_parts | c |<br>+-------------+-----+<br>| reilly | 704 |<br>| walter | 684 |<br>| kowski | 676 |<br>| onnelly | 662 |<br>| nnelly | 662 |<br>| kinson | 641 |<br>| tenberg | 626 |<br>| enberg | 626 |<br>| hermann | 417 |<br>| ermann | 417 |<br>+-------------+-----+<br>10 rows in set (1.59 sec) |
Using more than six characters gives us a much better selectivity.
|
1 |
select count(*) from email;<br>+----------+<br>| count(*) |<br>+----------+<br>| 318458 |<br>+----------+<br>1 row in set (0.04 sec)<br><br>select count(*) from email_trigram;<br>+----------+<br>| count(*) |<br>+----------+<br>| 2749000 |<br>+----------+<br>1 row in set (0.44 sec)<br><br>select count(*) from email_tib;<br>+----------+<br>| count(*) |<br>+----------+<br>| 2749000 |<br>+----------+<br>1 row in set (0.45 sec) |
In this test, I used 318458 random email addresses, and both methods created 2749000 additional rows.
Size on the disk:
|
1 |
45M email.ibd<br>221M email_tib.ibd<br>189M email_trigram.ibd |
As we expected they will use more space than the original table.
If there is no built in solution or index in MySQL that can help or solve your problem, do not give up. Many times, with small modifications, you can create your own index table or use other tricks.
In this specific case, if you are willing to sacrifice some additional disk space you can speed up your queries a lot with the right method. Trigram was not the best option, but I can see use cases where it could be better.
This is just one possible solution, there could be an even better one. If you know one, please let me know.