Lesson 2 of 15
19. Search and Inverted Indexes

19.1 Why doesn't `LIKE '%word%'` scale?

3 min read+10 XP

In the library: Without the cards, finding "every book about databases" means walking every shelf and opening every book. It works for a room of 50 books. Not for 2 million.

In the system: The first search anyone writes:

sql

a sorted index can jump to a prefix; a word in the middle has nowhere to jump to.

Figure: prefix matches can use a sorted index; "anywhere" matches can't.

The problems:

  • No index can help. A B-tree (Chapter 9) is sorted, so it can find titles that start with "data" (LIKE 'data%'), like finding a word in a dictionary. But "database anywhere in the text" has no starting point, so the database reads every row. With 2 million rows of about 1 KB each and a disk reading 500 MB/s, that's about 4 seconds per search, before anyone else is searching.
  • No understanding of words. "database" won't match "Databases" in some collations, or "DB", and "data" matches "database" and "updatable" alike.
  • No ranking. Every match is equal: a book titled "Databases" and one that mentions the word once in a 2,000-word description come back in whatever order.

Some databases add full-text search (PostgreSQL's tsvector with a GIN index, MySQL's FULLTEXT), which is the same idea as this chapter, built in. For a serious search feature, teams usually use a search engine: Elasticsearch, OpenSearch, Solr or similar.

Memory code: "A word in the middle has nowhere to jump to."