TechnicalEloquent performance

Eloquent performanceLesson 12 of 28

Fuzzier Searching With Regular Expressions

Need to search a transformed value? Precompute it in an indexed generated column.

2 min readIntermediateLesson

Eloquent performance12

The problem

Searching "Tim OReilly" doesn't find "Tim O'Reilly". People must type names exactly.

The fix

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.

✕ Instead of this

$query->whereRaw(
    "regexp_replace(first_name, '[^A-Za-z0-9]', '') like ?",
    [$term]
);
// calculated for every row, no index

✓ Do this

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);

The benefit

Fuzzy matching ("OReilly" finds "O'Reilly") at under 7 ms instead of ~595 ms.

Results

Search time

~595 ms<7 ms

99% lower

regex in the query vs. indexed generated columns

Why it works

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.

Watch out

  • Drop the old plain name indexes once nothing uses them. Indexes cost disk space and slow down writes.
  • If you do use whereRaw, pass values as bindings (?) to avoid SQL injection.

Frame from lesson 12

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.

Key takeaway

Need to search a transformed value? Precompute it in an indexed generated column.

Check yourself

Why was whereRaw("regexp_replace(first_name, ...) like ?") so slow?

Reveal answer

✓ Answer

Expressions on a column almost never use an index, so every row was processed.