Ô tìm sản phẩm hồi mới launch chạy ngon với 2.000 sản phẩm. Một năm sau catalogue lên 400.000 dòng, và mỗi lần gõ phím trong ô tìm kiếm là bắn ra một query mất 1,9 giây. Slow query log đầy những câu WHERE title LIKE '%tai nghe%' OR description LIKE '%tai nghe%'. Tệ hơn nữa, user than là gõ "tai nghe khong day" không ra gì, vì sản phẩm ghi "Tai nghe không dây", còn gõ "headphones wireless" thì sót mất "wireless headphones".
LIKE là bộ so khớp pattern, không phải search engine. Nó không xài được index khi wildcard nằm đầu, không biết gì về từ hay độ liên quan, và so từng ký tự y chang. MySQL có full-text engine thiệt sự trong InnoDB từ bản 5.6, Laravel cũng hỗ trợ tận răng. Nhiều khi nhiêu đó là đủ, chưa cần dựng thêm service tìm kiếm riêng.
Vì sao LIKE không scale
B-tree index được sắp theo giá trị của cột tính từ ký tự đầu tiên. Nhờ vậy LIKE 'tai nghe%' là một range scan trên index: tìm entry đầu tiên bắt đầu bằng "tai nghe" rồi đọc tới. LIKE '%tai nghe%' thì không cho engine điểm xuất phát nào, nên nó đọc mọi dòng và so chuỗi con trên từng dòng.
-- Leading wildcard: no B-tree index can help, every row is read and compared
SELECT id, title FROM products
WHERE title LIKE '%tai nghe%' OR description LIKE '%tai nghe%'
ORDER BY id DESC
LIMIT 20;
-- Prefix only: can use an index on title, but only finds titles that START with the term
SELECT id, title FROM products WHERE title LIKE 'tai nghe%' LIMIT 20;
EXPLAIN câu đầu cho ra type: ALL. Chi phí tăng tuyến tính theo kích thước bảng và nhân lên với mỗi cột OR. Thêm nữa, kết quả sắp theo id chứ không theo mức độ khớp, nên sản phẩm có chữ "tai nghe" chôn ở đoạn thứ sáu của mô tả cũng xếp ngang với sản phẩm tên đúng "Tai nghe".
FULLTEXT index chạy ra sao
FULLTEXT index là một inverted index: cuốn từ điển chứa mọi từ (token) trong các cột được index, mỗi từ trỏ tới những dòng chứa nó. Tìm ba từ thành ba lần tra từ điển rồi gộp kết quả, khỏi scan. InnoDB còn giữ thống kê về từ, nên tính được điểm relevance dựa trên số lần từ xuất hiện trong một dòng và độ hiếm của nó trên cả bảng.
ALTER TABLE products ADD FULLTEXT INDEX products_title_description_fulltext (title, description);
-- Natural language mode: relevance-ranked, rows come back sorted by score
SELECT id, title,
MATCH(title, description) AGAINST('wireless noise cancelling headphones') AS score
FROM products
WHERE MATCH(title, description) AGAINST('wireless noise cancelling headphones')
LIMIT 20;
Hai chi tiết hay làm người ta vấp:
- Danh sách cột trong
MATCH(...)phải khớp chính xác với danh sách cột của một FULLTEXT index.MATCH(title)sẽ không xài index trên(title, description); cần cả hai thì tạo index riêng. - Ở natural language mode, khi
MATCHnằm trongWHEREvà mình không thêmORDER BY, các dòng trả về đã sắp theo relevance. Select lại đúng biểu thứcMATCHđó làmscorelà miễn phí; MySQL chỉ tính một lần.
Đây là cách chọn giữa các phương án trong bài:
Natural language mode và boolean mode
Natural language mode (mặc định) coi chuỗi tìm kiếm là một túi từ. Dòng nào chứa bất kỳ từ nào cũng khớp, xếp theo relevance. Nó dễ tính, hợp với kiểu ô tìm "gõ gì đó, ra kết quả sát nhất". WITH QUERY EXPANSION chạy tìm kiếm hai lần, lần hai thêm từ lấy từ mấy kết quả đầu. Có ích với query rất ngắn, còn lại thì toàn thêm nhiễu.
Boolean mode cho mình toán tử và không tự sắp xếp:
-- Boolean mode: + must contain, - must not contain, * prefix, "..." exact phrase
SELECT id, title,
MATCH(title, description) AGAINST('+headphone* +wireless -refurbished' IN BOOLEAN MODE) AS score
FROM products
WHERE MATCH(title, description) AGAINST('+headphone* +wireless -refurbished' IN BOOLEAN MODE)
ORDER BY score DESC
LIMIT 20;
SELECT id, title FROM products
WHERE MATCH(title, description) AGAINST('+"tai nghe" +bluetooth' IN BOOLEAN MODE);
| Toán tử | Ý nghĩa |
|---|---|
+word |
bắt buộc phải có |
-word |
bắt buộc không có |
word* |
khớp tiền tố: headphone* khớp headphones |
"two words" |
đúng cụm, các từ đứng liền và đúng thứ tự |
>word <word |
tăng hoặc giảm mức đóng góp của từ đó |
| không toán tử | tùy chọn, có thì điểm cao hơn |
Với ô tìm kiếm thông thường, "từ nào cũng phải có, cho phép tiền tố" (+word* cho mỗi từ) cho kết quả đúng như user mong đợi, nên boolean mode kèm phép biến đổi đó là lựa chọn quen thuộc trên production. Nhớ luôn thêm ORDER BY score DESC ở boolean mode, vì nó không tự sắp giùm mình.
Tiếng Việt và chữ CJK
Full-text search phụ thuộc vào cách văn bản được cắt thành token. Parser mặc định cắt theo khoảng trắng và dấu câu, chạy được cho tiếng Anh và cả tiếng Việt, vì tiếng Việt viết các âm tiết cách nhau bằng khoảng trắng. Có hai cái bẫy riêng cho tiếng Việt.
Âm tiết ngắn bị bỏ. InnoDB bỏ qua token ngắn hơn innodb_ft_min_token_size, mặc định là 3. Rất nhiều âm tiết tiếng Việt chỉ có một hai chữ cái: "đi", "ăn", "cà", "xe", "ô". Tìm "xe máy" ở boolean mode với +xe* là không ra gì, vì "xe" chưa từng được index. Hạ innodb_ft_min_token_size xuống 2 (hoặc 1) trong my.cnf, restart, rồi rebuild các FULLTEXT index. Coi luôn danh sách stopword mặc định (INFORMATION_SCHEMA.INNODB_FT_DEFAULT_STOPWORD) vì nó thiên về tiếng Anh.
Dấu. User gõ "tai nghe khong day" cũng nhiều như "tai nghe không dây". Thay vì phụ thuộc chi tiết của collation, lưu một cột search_text đã chuẩn hóa và bỏ dấu rồi tìm trên cột đó. Str::ascii() của Laravel đổi "Tai nghe không dây" thành "Tai nghe khong day", kể cả "đ" thành "d".
Tiếng Trung, Nhật, Hàn không có khoảng trắng giữa các từ, nên parser mặc định coi cả câu là một token. MySQL có sẵn ngram parser cho chuyện này: nó index mọi chuỗi liên tiếp dài ngram_token_size ký tự (mặc định 2), nên "東京都" được index thành "東京" và "京都". ngram parser bỏ qua innodb_ft_min_token_size và xài ngram_token_size.
-- my.cnf, needs a restart, then rebuild the index
-- [mysqld]
-- innodb_ft_min_token_size = 2
-- ngram_token_size = 2
ALTER TABLE products DROP INDEX products_title_description_fulltext;
ALTER TABLE products
ADD FULLTEXT INDEX products_search_ngram (title, description) WITH PARSER ngram;
SELECT id, title FROM products
WHERE MATCH(title, description) AGAINST('"東京"' IN BOOLEAN MODE);
ngram cũng chạy được với tiếng Việt, nhưng nó index các mảnh hai chữ cái vắt ngang ranh giới từ, nên kết quả nhiễu và index bự hơn nhiều. Với tiếng Việt, parser mặc định cộng minimum token size thấp hơn và một cột không dấu thường là combo ngon hơn.
Cài đặt trong Laravel
Schema builder có fullText() để tạo index, query builder có whereFullText() / orWhereFullText(), trên MySQL sẽ compile thành MATCH ... AGAINST. Đầu tiên là migration, thêm cột đã chuẩn hóa cạnh index trên các cột gốc:
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('products', function (Blueprint $table) {
$table->text('search_text')->nullable()->after('description');
$table->fullText(['title', 'description']);
$table->fullText('search_text');
});
}
public function down(): void
{
Schema::table('products', function (Blueprint $table) {
$table->dropFullText(['title', 'description']);
$table->dropFullText(['search_text']);
$table->dropColumn('search_text');
});
}
};
Giữ search_text luôn đồng bộ từ model, để đường save nào cũng cập nhật nó:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
final class Product extends Model
{
protected static function booted(): void
{
static::saving(function (Product $product) {
$product->search_text = Str::of($product->title . ' ' . strip_tags((string) $product->description))
->ascii()
->lower()
->squish()
->value();
});
}
}
Rồi tới service tìm kiếm, biến input của user thành boolean query an toàn. Input của user bắt buộc phải làm sạch: một dấu -, * hay một dấu " lẻ loi là đổi nghĩa query hoặc làm MySQL từ chối luôn.
namespace App\Search;
use App\Models\Product;
use Illuminate\Contracts\Pagination\Paginator;
use Illuminate\Support\Str;
final class ProductSearch
{
private const OPERATORS = ['+', '-', '<', '>', '(', ')', '~', '*', '"', '@'];
public function search(string $input, int $perPage = 20): Paginator
{
$terms = collect(preg_split('/\s+/u', Str::of($input)->ascii()->lower()->value(), -1, PREG_SPLIT_NO_EMPTY))
->map(fn (string $word) => str_replace(self::OPERATORS, '', $word))
->filter(fn (string $word) => mb_strlen($word) >= 2)
->unique()
->take(8);
if ($terms->isEmpty()) {
return Product::query()->latest('id')->simplePaginate($perPage);
}
$against = $terms->map(fn (string $word) => "+{$word}*")->implode(' ');
return Product::query()
->select('*')
->selectRaw('MATCH(search_text) AGAINST(? IN BOOLEAN MODE) AS score', [$against])
->whereFullText('search_text', $against, ['mode' => 'boolean'])
->orderByDesc('score')
->orderByDesc('id')
->simplePaginate($perPage);
}
}
whereFullText nhận ['mode' => 'boolean'] cho boolean mode và ['expanded' => true] cho query expansion. Không có helper sắp theo relevance, nên score lấy từ selectRaw kèm binding rồi đưa vô orderByDesc. Giới hạn số từ để bảo vệ server khỏi mấy ông dán nguyên một đoạn văn.
Kiểm thử tìm kiếm
Hành vi full-text phụ thuộc engine thật, nên mấy test này cần MySQL chứ không phải SQLite. Trỏ database test vô một container MySQL trên CI. Thêm một cái bẫy: InnoDB chỉ đưa dòng vô FULLTEXT index lúc commit, nên test xài RefreshDatabase (bọc mỗi test trong một transaction) sẽ không thấy dữ liệu chính nó vừa insert. Dùng DatabaseTruncation hoặc DatabaseMigrations cho file test tìm kiếm.
use App\Models\Product;
use App\Search\ProductSearch;
beforeEach(function () {
Product::factory()->create(['title' => 'Tai nghe Bluetooth chống ồn', 'description' => 'Pin 30 giờ']);
Product::factory()->create(['title' => 'Loa Bluetooth mini', 'description' => 'Chống nước IPX7']);
Product::factory()->create(['title' => 'Tai nghe có dây', 'description' => 'Jack 3.5mm']);
});
it('finds products without accents and ranks the best match first', function () {
$results = app(ProductSearch::class)->search('tai nghe bluetooth');
expect($results->pluck('title')->all())->toBe(['Tai nghe Bluetooth chống ồn']);
});
it('matches word prefixes', function () {
$results = app(ProductSearch::class)->search('blue');
expect($results)->toHaveCount(2);
});
it('treats boolean operators in user input as plain text', function () {
$results = app(ProductSearch::class)->search('+loa -(bluetooth) "mini');
expect($results->pluck('title')->all())->toBe(['Loa Bluetooth mini']);
});
it('falls back to latest products for empty input', function () {
expect(app(ProductSearch::class)->search(' * + '))->toHaveCount(3);
});
Test toán tử là quan trọng nhất. Không làm sạch thì -(bluetooth) sẽ loại hết sản phẩm Bluetooth, còn dấu nháy lẻ có thể gây lỗi cú pháp trong AGAINST.
Những lỗi hay gặp
- Cột trong
MATCHkhông khớp index nào. Sẽ gặpCan't find FULLTEXT index matching the column list. Tạo index đúng bộ cột mình query. - Từ ngắn bị lờ đi âm thầm. Minimum token size và stopword làm query "xe", "go" hay "it" trả về rỗng, không báo lỗi gì. Chỉnh
innodb_ft_min_token_sizevà bảng stopword cho hợp ngôn ngữ. - Trông chờ sửa lỗi gõ. "headphnoes" sẽ không khớp "headphones". FULLTEXT không có fuzzy matching.
- Test trong transaction. Dòng chưa commit thì chưa nằm trong FULLTEXT index. Test pass ở local trên SQLite với fallback
LIKErồi fail trên production, hoặc ngược lại. - Đưa input thô vô boolean mode. Lọc bỏ
+ - < > ( ) ~ * " @hoặc tự dựng biểu thức.
Khi nào xài LIKE, FULLTEXT hay search engine
LIKE ổn cho tra cứu tiền tố trên cột có index (SKU, số điện thoại, autocomplete username) và cho bảng nhỏ, scan không tốn gì.
FULLTEXT của MySQL hợp khi:
- mình tìm từ trong tiêu đề và mô tả, cỡ vài trăm ngàn tới vài triệu dòng;
- "từ nào cũng phải có, xếp theo relevance" là đủ xài;
- mình muốn một database duy nhất, nhất quán theo transaction, không phải chạy thêm service.
Meilisearch, Typesense hay Elasticsearch/OpenSearch, thường đi qua Laravel Scout, đáng thêm một mảnh ghép khi:
- user trông chờ sửa lỗi gõ, từ đồng nghĩa, "có phải bạn muốn tìm";
- cần facet có đếm số (thương hiệu, khoảng giá, đánh giá) ở mọi lần tìm;
- xếp hạng cần quy tắc riêng: ưu tiên hàng còn, độ mới, độ phổ biến;
- cần phân tích theo ngôn ngữ như stemming, hoặc tìm trên hàng chục triệu document.
Chuyển sau này với Scout không phải viết lại. Index một model bằng cách thêm trait và mảng searchable:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Laravel\Scout\Searchable;
final class Article extends Model
{
use Searchable;
public function toSearchableArray(): array
{
return [
'id' => $this->id,
'title' => $this->title,
'body' => strip_tags($this->body),
'category' => $this->category?->name,
'published_at' => $this->published_at?->timestamp,
];
}
}
Scout còn có engine database xài whereFullText cho các cột đánh dấu bằng attribute SearchUsingFullText, nên mình bắt đầu trên MySQL sau API của Scout, tới khi yêu cầu tới thì đổi driver sang Meilisearch. Với ô tìm sản phẩm hồi đầu, FULLTEXT index trên cột search_text không dấu cộng minimum token size thấp hơn đã kéo query từ 1,9 giây xuống dưới 20 ms, và "tai nghe khong day" cuối cùng cũng ra đúng tai nghe không dây.
Thử thách
Luyện tập ngay điều vừa học. Viết lời giải, mở gợi ý nếu bí.
Đề bài
Viết to_boolean_query(input, minLength = 3) bằng PHP và toBooleanQuery(input, minLength = 3) bằng JavaScript. Hàm biến input thô từ ô tìm kiếm thành biểu thức boolean mode an toàn cho MySQL. Trước tiên lấy ra mọi cụm nằm trọn trong cặp nháy kép và xóa chúng khỏi input. Với mỗi cụm, thay các ký tự + - < > ( ) ~ * " @ bằng khoảng trắng, gộp khoảng trắng liên tiếp thành một, trim và chuyển chữ thường; nếu không rỗng thì xuất +"cụm". Sau đó tách phần còn lại theo khoảng trắng; với mỗi từ bỏ các ký tự trên, chuyển chữ thường, và chỉ xuất +từ* khi từ có ít nhất minLength ký tự (đếm ký tự chứ không đếm byte, chữ tiếng Việt tính là một). Xuất mọi cụm trước, rồi tới các từ, mỗi nhóm giữ thứ tự trong input, bỏ phần tử trùng y chang (giữ cái đầu), nối bằng một khoảng trắng. Input rỗng hoặc toàn toán tử thì trả chuỗi rỗng. Dấu nháy lẻ không tạo thành cụm: nó chỉ bị bỏ khỏi từ chứa nó.
Code khởi tạo
function to_boolean_query(string $input, int $minLength = 3): string
{
// TODO: extract complete "quoted phrases" first and remove them from the input
// TODO: for each phrase: strip the characters + - < > ( ) ~ * " @, collapse whitespace,
// trim, lowercase; keep non-empty phrases as +"phrase"
// TODO: split the rest on whitespace; strip the same characters from each word, lowercase,
// keep words with at least $minLength characters as +word*
// TODO: phrases first, then words, both in input order, no duplicates, joined by one space
}
function toBooleanQuery(input, minLength = 3) {
// TODO: extract complete "quoted phrases" first and remove them from the input
// TODO: for each phrase: strip the characters + - < > ( ) ~ * " @, collapse whitespace,
// trim, lowercase; keep non-empty phrases as +"phrase"
// TODO: split the rest on whitespace; strip the same characters from each word, lowercase,
// keep words with at least minLength characters as +word*
// TODO: phrases first, then words, both in input order, no duplicates, joined by one space
throw new Error('TODO');
}
Lời giải của bạn
Gợi ý
Đã mở hết gợi ýXài regex "([^"]*)" để tìm các cụm trọn vẹn, rồi thay chính các match đó bằng khoảng trắng trước khi tách từ.
PHP thì xài mb_strtolower và mb_strlen; JavaScript đếm ký tự bằng [...word].length.
Set trong JavaScript hay array_unique trong PHP bỏ trùng mà vẫn giữ thứ tự lần xuất hiện đầu.
function to_boolean_query(string $input, int $minLength = 3): string
{
$strip = ['+', '-', '<', '>', '(', ')', '~', '*', '"', '@'];
$parts = [];
preg_match_all('/"([^"]*)"/u', $input, $matches);
$rest = preg_replace('/"[^"]*"/u', ' ', $input);
foreach ($matches[1] as $phrase) {
$clean = mb_strtolower(trim(preg_replace('/\s+/u', ' ', str_replace($strip, ' ', $phrase))));
if ($clean !== '') {
$parts[] = '+"' . $clean . '"';
}
}
foreach (preg_split('/\s+/u', $rest, -1, PREG_SPLIT_NO_EMPTY) as $word) {
$clean = mb_strtolower(str_replace($strip, '', $word));
if (mb_strlen($clean) >= $minLength) {
$parts[] = '+' . $clean . '*';
}
}
return implode(' ', array_values(array_unique($parts)));
}
function toBooleanQuery(input, minLength = 3) {
const strip = /[+\-<>()~*"@]/g;
const parts = [];
for (const match of input.matchAll(/"([^"]*)"/g)) {
const clean = match[1].replace(strip, ' ').replace(/\s+/g, ' ').trim().toLowerCase();
if (clean !== '') parts.push(`+"${clean}"`);
}
const rest = input.replace(/"[^"]*"/g, ' ');
for (const word of rest.split(/\s+/).filter(Boolean)) {
const clean = word.replace(strip, '').toLowerCase();
if ([...clean].length >= minLength) parts.push(`+${clean}*`);
}
return [...new Set(parts)].join(' ');
}

