Skip to content

Commit 68c4202

Browse files
add relevance scoring for single-field prefix searches
Improvements: - Single-field prefix searches now sort by field length (shorter = more relevant) - Exact matches like "Wilma" will appear before longer matches like "Wilmaaaa" - Uses LENGTH() function which is compatible across MySQL, PostgreSQL, and SQLite Technical details: - Added orderByRaw("LENGTH({$field}) ASC") to scopeEncryptedPrefix - Multi-field searches remain unsorted due to database function compatibility - For best results with sorted relevance, use single-field prefix searches Example: Client::encryptedPrefix('first_names', 'Wilma')->get() // Returns: Wilma, Wilmar, Wilmaaaa (sorted by length)
1 parent ad42d5e commit 68c4202

File tree

1 file changed

+5
-2
lines changed

1 file changed

+5
-2
lines changed

src/Traits/HasEncryptedSearchIndex.php

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -349,15 +349,16 @@ public function scopeEncryptedPrefix(Builder $query, string $field, string $term
349349
return $query->whereIn($this->getQualifiedKeyName(), $modelIds);
350350
}
351351

352-
// Fallback to database
352+
// Fallback to database with relevance sorting
353+
// Sort by field length (shorter matches = more relevant)
353354
return $query->whereIn($this->getQualifiedKeyName(), function ($sub) use ($field, $tokens) {
354355
$sub->select('model_id')
355356
->from('encrypted_search_index')
356357
->where('model_type', static::class)
357358
->where('field', $field)
358359
->where('type', 'prefix')
359360
->whereIn('token', $tokens);
360-
});
361+
})->orderByRaw("LENGTH({$field}) ASC");
361362
}
362363

363364
/**
@@ -408,6 +409,8 @@ public function scopeEncryptedPrefixMulti(Builder $query, array $fields, string
408409
}
409410

410411
// Fallback to database - use OR logic for multiple fields
412+
// Note: Multi-field searches don't have relevance sorting due to database compatibility
413+
// Use single-field searches for relevance-sorted results
411414
return $query->whereIn($this->getQualifiedKeyName(), function ($sub) use ($fields, $tokens) {
412415
$sub->select('model_id')
413416
->from('encrypted_search_index')

0 commit comments

Comments
 (0)