Capítulo 4

Storage

PostgreSQL + pgvector: o banco vetorial que armazena embeddings para busca semântica de alta performance.

🏗️ Arquitetura do Sistema

PostgreSQLpgvector ExtensionHNSW IndexvecStore EmbeddingsRAGServiceask(question)search(query)OpenAI APItext-embedding-3-smallgenerate()LLM ResponseContexto + PerguntaRetrievalUser1Chunk text2Generate embedding3Store in pgvector

⚙️ Configuração

1. Instalar extensão pgvector

PostgreSQL Terminal
-- Via SQL direto
CREATE EXTENSION IF NOT EXISTS vector;

-- Ou via Laravel Migration
DB::statement('CREATE EXTENSION IF NOT EXISTS vector');

📦 Migration para Articles

database/migrations/xxxx_create_articles_table.php
<?php
return new class extends Migration
{
    public function up(): void
    {
        Schema::create("string">'articles', function (Blueprint $table) {
            $table->id();
            $table->string("string">'title');
            $table->text("string">'content');
            $table->text("string">'chunk');           // Texto original
            $table->vector("string">'embedding', 1536); // Vetor 1536 dim
            $table->unsignedInteger("string">'chunk_index')->default(0);
            $table->foreignId("string">'user_id')->constrained();
            $table->timestamps();
        });

        // Índice HNSW para busca vetorial rápida
        DB::statement('
            CREATE INDEX articles_embedding_hnsw_idx 
            ON articles USING hnsw (embedding vector_cosine_ops)
        ');
    }
};

⚡ Por que HNSW?

✅ HNSW

  • Busca aproximada com alta precisão (~95%)
  • Performance consistente (dataset de qualquer tamanho)
  • Rebuild automático
  • Melhor para produção

⚠️ IVFFlat

  • Depende de clustering inicial
  • Performance degrada com escala
  • Build manual necessário
  • Usar só para datasets pequenos