28 lines
904 B
PHP
28 lines
904 B
PHP
<?php
|
|
|
|
namespace App\Repositories;
|
|
|
|
use App\DTOs\ArticleCandidateDTO;
|
|
use App\Models\Article;
|
|
use App\Repositories\Contracts\ArticleRepositoryInterface;
|
|
use Illuminate\Support\Facades\DB;
|
|
|
|
class ArticleRepository implements ArticleRepositoryInterface
|
|
{
|
|
public function findSimilarByEmbedding(array $embedding, int $limit = 5): array
|
|
{
|
|
$vector = '['.implode(',', array_map(static fn ($value) => (float) $value, $embedding)).']';
|
|
|
|
$rows = Article::query()
|
|
->select('articles.*')
|
|
->selectRaw('embedding <=> ?::vector as distance', [$vector])
|
|
->whereNotNull('embedding')
|
|
->orderByRaw('embedding <=> ?::vector', [$vector])
|
|
->limit($limit)
|
|
->get();
|
|
|
|
return $rows
|
|
->map(fn (Article $article) => ArticleCandidateDTO::fromArticle($article, (float) $article->distance))
|
|
->all();
|
|
}
|
|
} |