Searching "Tim OReilly" doesn't find "Tim O'Reilly". People must type names exactly.
Search time
~595 ms<7 ms
99% lower
regex in the query vs. indexed generated columns
Eloquent performanceLesson 12 of 28
Need to search a transformed value? Precompute it in an indexed generated column.
2 min readIntermediateLesson
Searching "Tim OReilly" doesn't find "Tim O'Reilly". People must type names exactly.
Strip punctuation from both the search term and the stored names. Store the stripped names in indexed generated columns so the database doesn't recalculate them.
$query->whereRaw(
"regexp_replace(first_name, '[^A-Za-z0-9]', '') like ?",
[$term]
);
// calculated for every row, no index
Migration:
$table->string('name_normalized')->virtualAs("regexp_replace(name, '[^A-Za-z0-9]', '')")->index();
Query:
$term = preg_replace('/[^A-Za-z0-9]/', '', $term).'%';
$query->where('first_name_normalized', 'like', $term)
->orWhere('last_name_normalized', 'like', $term);
Fuzzy matching ("OReilly" finds "O'Reilly") at under 7 ms instead of ~595 ms.
Search time
~595 ms<7 ms
99% lower
regex in the query vs. indexed generated columns
Running a function like regexp_replace() on a column inside WHERE means the index can't be used: the database must compute it for every row. A virtual generated column stores the result as if it were a real column, and that can be indexed.
whereRaw, pass values as bindings (?) to avoid SQL injection.
The users migration with virtual generated columns, e.g. first_name_normalized virtualAs("regexp_replace(first_name, '[^A-Za-z0-9]', '')")->index(). Each expression gets its own index.
Need to search a transformed value? Precompute it in an indexed generated column.
Why was whereRaw("regexp_replace(first_name, ...) like ?") so slow?
✓ Answer
Expressions on a column almost never use an index, so every row was processed.