mdcms/neuraldb-docs/pages/sdk-go.md

2.1 KiB

title sort section-id keywords description language
Go SDK 120 client-sdks Go, Golang, SDK, client, connection pool, query builder, pgx The NeuralDB Go SDK — installation, connection pooling, and vector query builder en

Go SDK

Built on pgx, the high-performance PostgreSQL driver for Go.

Installation

go get github.com/neuraldb/neuraldb-go

Requires Go 1.21+.

Connecting

client, err := neuraldb.Connect(ctx, "postgresql://neuraldb:password@localhost:5432/mydb")
if err != nil { log.Fatal(err) }
defer client.Close(ctx)

Connection Pool

config, _ := pgxpool.ParseConfig(os.Getenv("NEURALDB_URL"))
config.MaxConns = 20
config.MinConns = 5
pool, _ := neuraldb.NewPool(ctx, config)

Working with Vectors

v := types.NewVector([]float32{0.023, -0.187, 0.412})

func InsertDocument(ctx context.Context, pool *neuraldb.Pool, doc Document) error {
    _, err := pool.Exec(ctx,
        `INSERT INTO documents (id, content, embedding) VALUES ($1, $2, $3)`,
        doc.ID, doc.Content, doc.Embedding,
    )
    return err
}

func SemanticSearch(ctx context.Context, pool *neuraldb.Pool, queryEmbedding []float32, limit int) ([]SearchResult, error) {
    qv := types.NewVector(queryEmbedding)
    rows, err := pool.Query(ctx, `
        SELECT id, content, 1 - (embedding <=> $1) AS similarity
        FROM documents WHERE embedding IS NOT NULL
        ORDER BY embedding <=> $1 LIMIT $2
    `, qv, limit)
    if err != nil { return nil, err }
    defer rows.Close()
    var results []SearchResult
    for rows.Next() {
        var r SearchResult
        rows.Scan(&r.ID, &r.Content, &r.Similarity)
        results = append(results, r)
    }
    return results, rows.Err()
}

Transactions

pool.BeginTxFunc(ctx, pgx.TxOptions{}, func(tx pgx.Tx) error {
    for _, doc := range docs {
        _, err := tx.Exec(ctx,
            `INSERT INTO documents (content, embedding) VALUES ($1, $2)`,
            doc.Content, doc.Embedding,
        )
        if err != nil { return err }
    }
    _, err := tx.Exec(ctx, `UPDATE stats SET doc_count = doc_count + $1`, len(docs))
    return err
})