TechnicalEloquent performance

Eloquent performanceLesson 24 of 28

Full Text Searching With Rankings

Searching documents? Full text index + MATCH AGAINST, and don't override the score order.

1 min readIntermediateLesson

Eloquent performance24

The problem

Search the body of 500 blog posts and show the most relevant first.

The fix

Add a full text index and use MATCH ... AGAINST, which also returns a relevance score.

✕ Instead of this

Post::where('body', 'like', '%'.$search.'%')
    ->latest('published_at')
    ->get();
// scans every post, no relevance ranking

✓ Do this

Post::query()
    ->when(request('search'), function ($query, $search) {
        $query->selectRaw('*, match(title, body) against(? in boolean mode) as score', [$search])
              ->whereRaw('match(title, body) against(? in boolean mode)', [$search]);
    }, function ($query) {
        $query->latest('published_at');
    })

The benefit

Uses the full text index and puts the most relevant posts first.

More detail

  1. Create the index (migrations didn't support it at the time):
DB::statement('CREATE FULLTEXT INDEX posts_fulltext_index ON posts(title, body) WITH PARSER ngram');
  1. Query in boolean mode. score is the relevance:
select id, title, match(title, body) against('fox' in boolean mode) as score
from posts
where match(title, body) against('fox' in boolean mode)

Why it works

MySQL orders by score automatically when there's no other ordering. Any orderBy overrides it, which is why the default ordering goes in when()'s third argument (the "otherwise" callback).

Watch out

  • The ngram parser (MySQL 5.7.6+) gave better results than the default in the author's experience.

Frame from lesson 24

The boolean-mode full text query in TablePlus returns the three fox posts. Adding the match() expression to the SELECT as score exposes the relevance ranking.

Key takeaway

Searching documents? Full text index + MATCH AGAINST, and don't override the score order.

Check yourself

Results come back in date order instead of relevance. What happened?

Reveal answer

✓ Answer

An orderBy was applied while searching. Put it in when()'s else-callback.