Case 1. Semantic search on vectors manually (pure PHP)
Ranking documents by cosine similarity of vectors
Below is a pure PHP semantic search example: both documents and query already have vector representations, then we compute cosine similarity, sort by score, and return the top-N most relevant documents.
Example of use
<?php
include 'code-en.php';
$query = [
'text' => 'speed up email sending',
'embedding' => [0.10, 0.84, 0.29, 0.58, 0.69],
];
foreach ($documents as &$document) {
$document['score'] = cosineSimilarity($query['embedding'], $document['embedding']);
}
unset($document);
usort($documents, function ($a, $b) {
return $b['score'] <=> $a['score'];
});
$topN = 5;
foreach (array_slice($documents, 0, $topN) as $document) {
echo $document['title'] . ' => ' . round($document['score'], 3) . PHP_EOL;
}
Documents:
Query: speed up email sending
Monitoring email delivery
Optimizing bulk email campaigns
Scaling PHP workers
RabbitMQ and background jobs
Configuring queues in Laravel
Kubernetes autoscaling
Redis queues in production
Traveling across Iceland
History of Ancient Rome
How to make coffee at home
Result:
Memory: 0.01 Mb
Time running: < 0.001 sec.
Monitoring email delivery => 0.999
Optimizing bulk email campaigns => 0.999
Scaling PHP workers => 0.998
RabbitMQ and background jobs => 0.996
Configuring queues in Laravel => 0.992