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

85 lines
2.1 KiB
Markdown

---
title: Go SDK
sort: 120
section-id: client-sdks
keywords: Go, Golang, SDK, client, connection pool, query builder, pgx
description: The NeuralDB Go SDK — installation, connection pooling, and vector query builder
language: en
---
# Go SDK
Built on `pgx`, the high-performance PostgreSQL driver for Go.
## Installation
```bash
go get github.com/neuraldb/neuraldb-go
```
Requires Go 1.21+.
## Connecting
```go
client, err := neuraldb.Connect(ctx, "postgresql://neuraldb:password@localhost:5432/mydb")
if err != nil { log.Fatal(err) }
defer client.Close(ctx)
```
### Connection Pool
```go
config, _ := pgxpool.ParseConfig(os.Getenv("NEURALDB_URL"))
config.MaxConns = 20
config.MinConns = 5
pool, _ := neuraldb.NewPool(ctx, config)
```
## Working with Vectors
```go
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
```go
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
})
```