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 code:

 
<?php

$documents 
= [
    [
        
'title' => 'Optimizing bulk email campaigns',
        
'embedding' => [0.120.880.330.550.71],
    ],
    [
        
'title' => 'Configuring queues in Laravel',
        
'embedding' => [0.180.790.410.600.66],
    ],
    [
        
'title' => 'RabbitMQ and background jobs',
        
'embedding' => [0.140.810.390.580.69],
    ],
    [
        
'title' => 'Scaling PHP workers',
        
'embedding' => [0.110.810.360.630.72],
    ],
    [
        
'title' => 'Redis queues in production',
        
'embedding' => [0.150.180.310.520.62],
    ],
    [
        
'title' => 'Monitoring email delivery',
        
'embedding' => [0.090.910.280.570.74],
    ],
    [
        
'title' => 'Kubernetes autoscaling',
        
'embedding' => [0.320.610.700.400.51],
    ],
    [
        
'title' => 'How to make coffee at home',
        
'embedding' => [0.910.040.150.080.02],
    ],
    [
        
'title' => 'History of Ancient Rome',
        
'embedding' => [0.840.120.100.210.07],
    ],
    [
        
'title' => 'Traveling across Iceland',
        
'embedding' => [0.730.180.220.190.11],
    ],
];

function 
cosineSimilarity(array $a, array $b): float {
    
$dotProduct 0.0;
    
$normA 0.0;
    
$normB 0.0;

    foreach (
$a as $i => $value) {
        
$dotProduct += $value $b[$i];

        
$normA += $value ** 2;
        
$normB += $b[$i] ** 2;
    }

    if (
$normA == 0.0 || $normB == 0.0) {
        return 
0.0;
    }

    return 
$dotProduct / (sqrt($normA) * sqrt($normB));
}