velr

package module
v0.2.33 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 4, 2026 License: MIT Imports: 19 Imported by: 0

README

Velr

Velr is an embedded property-graph database from Velr.ai, written in Rust, built on top of SQLite, and queried using the openCypher language.

It runs in-process and is designed for local, embedded, and edge use cases.

This module provides the Go bindings for Velr. It wraps a bundled native runtime with a C ABI and exposes an idiomatic Go API for executing Cypher queries, streaming result tables, working with transactions, decoding graph values, and importing or exporting Arrow data.

For the main Velr public entry point, see velr-ai/velr. For the Velr website, see velr.ai. For generated Go API documentation, see pkg.go.dev/github.com/velr-ai/velr-go-driver.

Community

We'd love to have you join the Velr community.


Release Status

Velr is currently in public alpha.

  • The Go API is still evolving.
  • Velr supports openCypher and passes all positive openCypher TCK tests. Exact error semantics are not guaranteed to match other openCypher implementations.
Schema Version 7 Compatibility

This release's current on-disk schema is version 7. Supported older databases can be opened with velr.Open or velr.OpenReadonly without changing the file. Reads continue to work on those databases, but writes (CREATE, MERGE, SET, DELETE, DETACH DELETE, and other mutating queries) are only available after migrating to the current schema version. This is intentional: migration is an explicit maintenance operation, not a side effect of opening a database.

Velr is already usable for real workflows and representative use cases, but rough edges remain and the API is not yet stable.

Fulltext search and vector search are available today through Cypher DDL and CALL syntax. API details may still evolve while Velr remains alpha.


Installation

Install the Go module:

go get github.com/velr-ai/velr-go-driver@latest

The module ships the supported Velr native runtime binaries. Applications do not need a Velr source checkout, Rust toolchain, or separate runtime package.

Supported bundled platforms:

  • darwin-universal
  • linux-x64-gnu
  • linux-arm64-gnu
  • win32-x64-msvc
Licensing In Simple Terms
  • The Go binding source code in this module is licensed under the MIT license in LICENSE.
  • The bundled native runtime binaries may be used and freely redistributed in unmodified form under the terms of LICENSE.runtime.

Quick Start

package main

import (
    "fmt"
    "log"

    velr "github.com/velr-ai/velr-go-driver"
)

func main() {
    db, err := velr.OpenInMemory()
    if err != nil {
        log.Fatal(err)
    }
    defer db.Close()

    err = db.RunWithParams("CREATE (:Person {name: $name, born: $born})", velr.Params{
        "name": "Keanu Reeves",
        "born": 1964,
    })
    if err != nil {
        log.Fatal(err)
    }

    rows, err := db.Query("MATCH (p:Person) RETURN p.name AS name, p.born AS born")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(rows)
}

Open a file-backed database instead of an in-memory database:

db, err := velr.Open("mygraph.db")

Open an existing database for reads only:

db, err := velr.OpenReadonly("mygraph.db")

OpenReadonly never creates, initializes, migrates, or repairs a database. The file must already exist and have a supported Velr schema version. Older supported databases, such as schema version 3, 4, 5, or 6 databases opened by a schema version 7 runtime, remain available for reads. Writes and features that require the current schema fail with a normal query error until the database is explicitly migrated.

Connections and active handles are not safe for concurrent use. Use one connection per goroutine when you need parallelism.


Schema Migration

Velr does not migrate supported older databases automatically on open. Use the driver migration API, or run MIGRATE DATABASE, from maintenance code when you intend to update the on-disk schema. See the release-status note above for the schema version 7 read/write compatibility behavior.

db, err := velr.Open("mygraph.db")
if err != nil {
    log.Fatal(err)
}
defer db.Close()

needs, err := db.NeedsMigration()
if err != nil {
    log.Fatal(err)
}
if needs {
    report, err := db.Migrate()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(report.Status, report.FromVersion, report.ToVersion, report.Steps)
}

The equivalent Cypher command is useful for scripts and tools that already work through query execution:

table, err := db.ExecOne("MIGRATE DATABASE")
if err != nil {
    log.Fatal(err)
}
defer table.Close()

Query Execution

Velr exposes four main ways to run Cypher:

  • Run executes Cypher and drains all result tables.
  • Exec returns a stream when a statement can produce multiple result tables.
  • ExecOne returns exactly one table.
  • Query converts one table into []map[string]any.

Convenience helpers such as RunWithParams, ExecOneWithParams, and QueryWithParams bind named Cypher parameters:

rows, err := db.QueryWithParams(
    "MATCH (p:Person {name:$name}) RETURN p.born AS born",
    velr.Params{"name": "Keanu Reeves"},
)

Query text uses $name; map keys omit the leading $. Parameters are values, not Cypher string interpolation.

Use MaxResultRows when you want a per-result-table row cap:

rows, err := db.Query(
    "MATCH (p:Person) RETURN p.name AS name ORDER BY name",
    velr.MaxResultRows(100),
)

Supported parameter values are nil, bool, signed and unsigned integers that fit int64, finite floats, string, json.RawMessage, lists, arrays, and maps with string keys. Convert structs to maps or explicit json.RawMessage before binding them.


Reading Results

For typed row handling, use Rows.NextInto or velr.Scan:

table, err := db.ExecOneWithParams(
    "MATCH (p:Person {name:$name}) RETURN p.name, p.born",
    velr.Params{"name": "Keanu Reeves"},
)
if err != nil {
    log.Fatal(err)
}
defer table.Close()

rows, err := table.Rows()
if err != nil {
    log.Fatal(err)
}
defer rows.Close()

var name string
var born int64
ok, err := rows.NextInto(&name, &born)
if err != nil {
    log.Fatal(err)
}
fmt.Println(ok, name, born)

Result helpers:

  • Table.ColumnCount and Table.ColumnNames inspect result metadata.
  • Table.Rows opens a row cursor.
  • Table.ForEachRow, Table.Collect, and Table.ToObjects collect results.
  • Rows.Next returns []Cell; Rows.NextInto scans into pointers.
  • Cell.Value returns plain Go values.
  • Cell.AsBool, AsInt64, AsFloat64, AsString, DecodeJSON, and AssignTo provide stricter conversions.
  • Cell.AsPropertyValue returns a typed velr.PropertyValue for scalar property values and lists.

Cell.AsProperty adds richer decoding for Velr graph and property values. Nodes become velr.Node, relationships become velr.Relationship, paths become velr.Path, and spatial GeoJSON values become velr.GeoJSON. Node.Properties and Relationship.Properties are map[string]velr.PropertyValue. Use PropertyValue.Type or PropertyValue.Kind() for the Velr kind, and PropertyValue.GoValue() when you want ordinary Go values.


Transactions And Savepoints

Use Transaction for commit-on-success and rollback-on-error:

err := db.Transaction(func(tx *velr.Tx) error {
    if err := tx.Run("CREATE (:Event {name:'start'})"); err != nil {
        return err
    }

    sp, err := tx.Savepoint()
    if err != nil {
        return err
    }

    if err := tx.Run("CREATE (:Event {name:'discard'})"); err != nil {
        _ = sp.Close()
        return err
    }
    return sp.Rollback()
})

Explicit transactions are available with BeginTx, Commit, Rollback, and Close. Closing an uncommitted transaction rolls it back.

Named savepoints use SavepointNamed, RollbackTo, and ReleaseSavepoint. Named savepoints are stack-like: release the most recently created active named savepoint first.

Savepoint.Release keeps changes after the savepoint, Savepoint.Rollback discards them, and Savepoint.Close closes the native handle without an explicit release or rollback.


Introspection

Use SHOW CURRENT GRAPH SHAPE to inspect the observed schema of the graph. It reports the shape present in stored data: node labels, relationship types, properties, observed value types, and counts. It is an observed shape surface, not a declared GQL graph type.

rows, err := db.Query(`
    SHOW CURRENT GRAPH SHAPE
    YIELD element_kind, element_name, property_name, observed_type, owner_count
    WHERE element_kind = 'node_property'
    RETURN element_name, property_name, observed_type, owner_count
`)

Use YIELD to compose the command with WHERE and RETURN. Plain SHOW CURRENT GRAPH SHAPE returns the default projection; YIELD * exposes the full current row shape.


OpenCypher Functions

The bundled runtime supports the following openCypher functions and constructors:

Graph and path: id, type, labels, keys, properties, length, nodes, and relationships.

Lists and predicates: size, head, last, tail, reverse, range, all, any, none, and single.

Strings and conversion: coalesce, toInteger, toString, toLower, trim, substring, and split.

Numeric: abs, ceil, rand, sign, and sqrt.

Temporal constructors and clocks: date, time, localtime, datetime, localdatetime, duration, datetime.fromepoch, datetime.fromepochmillis, and the .realtime, .transaction, and .statement variants for date, time, localtime, datetime, and localdatetime.

Aggregates: count, sum, avg, min, max, collect, percentileDisc, and percentileCont.


Fulltext search is available through normal Cypher execution. Define indexes with CREATE FULLTEXT INDEX and query them with CALL db.index.fulltext.queryNodes(...).

db, err := velr.Open("mygraph.db")
if err != nil {
    log.Fatal(err)
}
defer db.Close()

err = db.Run(`
    CREATE FULLTEXT INDEX paperText
    FOR (n:Paper) ON EACH [n.title, n.abstract]
`)
if err != nil {
    log.Fatal(err)
}

rows, err := db.QueryWithParams(`
    CALL db.index.fulltext.queryNodes('paperText', $query)
    YIELD node, score
    RETURN node, score
`, velr.Params{"query": `abstract:vector OR title:"query planning"`})

Fulltext indexes use a sidecar next to file-backed databases. The sidecar is kept up to date by writes and rebuilt on open if it is missing or corrupt.


Register an embedding callback, then reference it from CREATE VECTOR INDEX. Velr invokes the callback for index maintenance when indexed source values change and for text queries passed to CALL db.index.vector.queryNodes(...).

err := db.RegisterVectorEmbedder("toy", func(inputs []velr.VectorEmbeddingInput) ([][]float32, error) {
    out := make([][]float32, len(inputs))
    for i, input := range inputs {
        out[i] = embed(input.Text(), input.Dimensions)
    }
    return out, nil
})

The callback must return one finite []float32 embedding per input, with the exact dimension count requested by the index.

VectorEmbeddingInput includes index name, dimensions, purpose, entity kind, entity id, and selected fields. Each VectorEmbeddingField carries a typed PropertyValue; use field.Value.Type or field.Value.Kind() to inspect the Velr kind, field.Value.GoValue() for ordinary Go values, and VectorEmbeddingInput.Text() to join display strings for toy or local embedders.

Vector indexes use a sidecar next to file-backed databases.


Arrow

Table.ToArrowIPC exports a result table as Arrow IPC file bytes. BindArrowIPC imports Arrow IPC file bytes under a logical table name:

table, err := db.ExecOne("MATCH (m:Movie) RETURN m.title AS title")
if err != nil {
    log.Fatal(err)
}
defer table.Close()

ipc, err := table.ToArrowIPC()
if err != nil {
    log.Fatal(err)
}

if err := db.BindArrowIPC("_movies", ipc); err != nil {
    log.Fatal(err)
}

BindArrow and BindArrowChunks bind Arrow C Data Interface columns from whichever Go Arrow implementation your application uses. The ArrowArray pointers passed to BindArrow or BindArrowChunks are transferred to Velr by the ABI call. Do not release or reuse those arrays after calling; schemas and column names are borrowed only during the call.

After binding a logical name, read the rows from Cypher with UNWIND BIND(...):

if err := db.BindArrow("_people", columns); err != nil {
    log.Fatal(err)
}

if err := db.Run(`
    UNWIND BIND('_people') AS row
    CREATE (:Person {name: row.name, age: row.age})
`); err != nil {
    log.Fatal(err)
}

The arrow_columns example shows a complete Apache Arrow Go export using arrow/cdata and malloc-backed Arrow buffers.

Transactions also expose Tx.BindArrowIPC, Tx.BindArrow, and Tx.BindArrowChunks.


Explain

Use Explain or ExplainAnalyze on DB or Tx to inspect a query plan:

trace, err := db.Explain("MATCH (n) RETURN count(n)")
if err != nil {
    log.Fatal(err)
}
defer trace.Close()

compact, err := trace.CompactString()

For structured access, use PlanCount, PlanMeta, StepCount, StepMeta, StatementCount, StatementMeta, SQLitePlanCount, SQLitePlanDetail, SQLitePlanDetails, or Snapshot. For compact rendering use CompactLen, CompactBytes, CompactString, or WriteCompact.


Errors And Lifecycle

Runtime failures return *velr.Error with a native error code and message. Driver-side validation uses ordinary Go errors where no native call was made.

Explicitly close DB, Tx, Stream, TxStream, Table, Rows, Savepoint, and ExplainTrace values. Close is idempotent on all closeable handle types. Finalizers are present as a leak safety net, but explicit close keeps native resources deterministic.


Examples

Runnable examples live in github.com/velr-ai/velr-go-examples.

The examples cover basic queries, transactions and savepoints, schema migration, read-only open, fulltext search, vector search, Arrow IPC, and Arrow C Data column binding. They use the published Go module; you do not need a Velr source checkout.

License

The Go driver source is licensed under the MIT license in LICENSE. The bundled native runtime binaries are licensed separately under LICENSE.runtime.

Documentation

Overview

Package velr provides Go bindings for the embedded Velr graph database.

The package wraps the Velr native runtime through its public C ABI. The module embeds the supported native runtime binaries, materializes the selected runtime into the user cache directory on first use, and loads that exact ABI version. Applications do not need a Velr source checkout or separate runtime install.

OpenInMemory opens an ephemeral graph. Open opens or creates a file-backed graph. OpenReadonly opens an existing graph without creating, initializing, or migrating it.

Query execution is synchronous. DB.Run discards result tables, DB.Exec returns a stream for statements that can produce multiple tables, DB.ExecOne requires exactly one table, and DB.Query converts one table to []map[string]any. Transaction methods provide the same shape on Tx. QueryOptions carries named parameters and an optional max-result-row cap; the WithParams, RunWithParams, QueryWithParams, and related helpers are convenience wrappers.

Result data is exposed as Table, Rows, and Cell. Cell.Value returns plain Go values; stricter conversions are available through AsBool, AsInt64, AsFloat64, AsString, DecodeJSON, AssignTo, Scan, and Rows.NextInto. Cell.AsPropertyValue returns typed scalar/list property values. Cell.AsProperty decodes canonical Velr values into richer graph values such as Node, Relationship, Path, and GeoJSON. Node and Relationship properties are exposed as map[string]PropertyValue.

Transactions are explicit. DB.Transaction commits when its callback returns nil and rolls back when the callback returns an error. BeginTx gives direct access to Commit, Rollback, Close, Savepoint, SavepointNamed, RollbackTo, and ReleaseSavepoint.

SchemaVersion, CurrentSchemaVersion, NeedsMigration, and Migrate expose the driver migration API. Explain and ExplainAnalyze return ExplainTrace handles with both compact and structured plan access.

Fulltext search is available through Cypher. Vector indexes can use RegisterVectorEmbedder to call a synchronous Go VectorEmbedder; callback fields carry typed PropertyValue values. Arrow IPC bytes are supported with BindArrowIPC and Table.ToArrowIPC; Arrow C Data Interface columns are supported with BindArrow and BindArrowChunks. Bound Arrow names are consumed from Cypher with UNWIND BIND('name') AS row.

Handles are connection-affine: do not use the same DB, transaction, stream, table, row cursor, savepoint, or explain trace concurrently from multiple goroutines. Close handles explicitly when finished; finalizers are only a leak safety net.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func DecodePropertyJSON

func DecodePropertyJSON(data []byte) (any, error)

DecodePropertyJSON decodes Velr's canonical JSON cell representation.

Graph nodes, relationships, paths, and GeoJSON spatial values are returned as Node, Relationship, Path, and GeoJSON. Scalar values and lists are returned as PropertyValue. Generic objects are returned as map[string]any with decoded field values.

func Scan

func Scan(row []Cell, dest ...any) error

Scan assigns a row of cells into destination pointers.

Types

type ArrowChunk

type ArrowChunk struct {
	// Schema points to a struct ArrowSchema borrowed for the duration of BindArrowChunks.
	Schema unsafe.Pointer

	// Array points to a struct ArrowArray whose release ownership is transferred to Velr.
	Array unsafe.Pointer
}

ArrowChunk is one Arrow C Data Interface chunk for a logical column.

type ArrowColumn

type ArrowColumn struct {
	// Name is the logical column name exposed to Cypher.
	Name string

	// Schema points to a struct ArrowSchema borrowed for the duration of BindArrow.
	Schema unsafe.Pointer

	// Array points to a struct ArrowArray whose release ownership is transferred to Velr.
	Array unsafe.Pointer
}

ArrowColumn is one Arrow C Data Interface column.

Schema must point to a struct ArrowSchema and Array must point to a struct ArrowArray. The ArrowArray is transferred to Velr by BindArrow; the schema is borrowed only during the call.

type ArrowColumnChunks

type ArrowColumnChunks struct {
	// Name is the logical column name exposed to Cypher.
	Name string

	// Chunks contains Arrow arrays for this logical column in row order.
	Chunks []ArrowChunk
}

ArrowColumnChunks is a chunked Arrow C Data Interface column.

type Cell

type Cell struct {
	// Type identifies which value field is populated.
	Type CellType

	// Int64 contains integer values and boolean values encoded as 0 or 1.
	Int64 int64

	// Float64 contains floating-point values.
	Float64 float64

	// Bytes contains text or JSON bytes owned by the Go cell.
	Bytes []byte
}

Cell is one value in a result row.

func (Cell) AsBool

func (c Cell) AsBool() (bool, error)

AsBool converts a boolean cell to bool.

func (Cell) AsFloat64

func (c Cell) AsFloat64() (float64, error)

AsFloat64 converts a double cell to float64.

func (Cell) AsInt64

func (c Cell) AsInt64() (int64, error)

AsInt64 converts an integer cell to int64.

func (Cell) AsProperty

func (c Cell) AsProperty() (any, error)

AsProperty returns this cell as a decoded Velr value.

JSON cells are decoded with DecodePropertyJSON. Text cells stay text even when they begin with JSON-looking characters.

Example
package main

import (
	"fmt"
	"log"

	velr "github.com/velr-ai/velr-go-driver"
)

func main() {
	db, err := velr.OpenInMemory()
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	table, err := db.ExecOne("CREATE (p:Person {name: 'Ada'}) RETURN p")
	if err != nil {
		log.Fatal(err)
	}
	defer table.Close()

	cells, err := table.Collect()
	if err != nil {
		log.Fatal(err)
	}
	value, err := cells[0][0].AsProperty()
	if err != nil {
		log.Fatal(err)
	}
	node := value.(velr.Node)
	fmt.Println(node.Labels, node.Properties["name"].GoValue())
}

func (Cell) AsPropertyValue

func (c Cell) AsPropertyValue() (PropertyValue, error)

AsPropertyValue converts this cell to a typed Velr property value.

Graph result values such as nodes, relationships, and paths are not property values. For those JSON cells, use AsProperty and type-assert the graph value.

func (Cell) AsString

func (c Cell) AsString() (string, error)

AsString decodes text and JSON cells as UTF-8.

func (Cell) AssignTo

func (c Cell) AssignTo(dest any) error

AssignTo assigns this cell to a destination pointer.

func (Cell) DecodeJSON

func (c Cell) DecodeJSON(out any) error

DecodeJSON decodes a JSON cell into out.

func (Cell) String

func (c Cell) String() string

String returns a display rendering of the cell.

func (Cell) Value

func (c Cell) Value() any

Value converts the cell to a Go value.

JSON cells are decoded into interface values. Use String for the raw UTF-8 representation when you do not want JSON parsing.

type CellType

type CellType int

CellType identifies a value returned by Velr.

const (
	// Null is a null result cell.
	Null CellType = iota

	// Bool is a boolean result cell.
	Bool

	// Int64 is a signed 64-bit integer result cell.
	Int64

	// Double is a floating-point result cell.
	Double

	// Text is a UTF-8 text result cell.
	Text

	// JSON is a UTF-8 JSON result cell.
	JSON
)

func (CellType) String

func (t CellType) String() string

String returns the stable text form of t.

type DB

type DB struct {
	// contains filtered or unexported fields
}

DB is a Velr database connection.

func Open

func Open(path string) (*DB, error)

Open opens a file-backed Velr database for reading and writing.

func OpenInMemory

func OpenInMemory() (*DB, error)

OpenInMemory opens an in-memory Velr database.

Example
package main

import (
	"fmt"
	"log"

	velr "github.com/velr-ai/velr-go-driver"
)

func main() {
	db, err := velr.OpenInMemory()
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	if err := db.RunWithParams("CREATE (:Person {name: $name, born: $born})", velr.Params{
		"name": "Keanu Reeves",
		"born": 1964,
	}); err != nil {
		log.Fatal(err)
	}

	rows, err := db.Query("MATCH (p:Person) RETURN p.name AS name, p.born AS born")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(rows[0]["name"], rows[0]["born"])
}

func OpenReadonly

func OpenReadonly(path string) (*DB, error)

OpenReadonly opens an existing database in read-only mode.

Example
package main

import (
	"fmt"
	"log"

	velr "github.com/velr-ai/velr-go-driver"
)

func main() {
	db, err := velr.OpenReadonly("graph.db")
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	rows, err := db.Query("MATCH (n) RETURN count(n) AS nodes")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(rows[0]["nodes"])
}

func (*DB) BeginTx

func (db *DB) BeginTx() (*Tx, error)

BeginTx starts an explicit transaction.

func (*DB) BindArrow

func (db *DB) BindArrow(logical string, columns []ArrowColumn) error

BindArrow binds Arrow C Data Interface columns under a logical table name.

The ArrowArray pointers are transferred to Velr on success or failure of the ABI call. Do not use or release those ArrowArray values after calling. ArrowSchema pointers and column names are borrowed only during the call.

Example
package main

import (
	"log"
	"unsafe"

	velr "github.com/velr-ai/velr-go-driver"
)

func main() {
	db, err := velr.OpenInMemory()
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	var schemaPtr unsafe.Pointer
	var arrayPtr unsafe.Pointer
	err = db.BindArrow("people", []velr.ArrowColumn{{
		Name:   "name",
		Schema: schemaPtr,
		Array:  arrayPtr,
	}})
	if err != nil {
		log.Fatal(err)
	}
}

func (*DB) BindArrowChunks

func (db *DB) BindArrowChunks(logical string, columns []ArrowColumnChunks) error

BindArrowChunks binds chunked Arrow C Data Interface columns under a logical table name.

func (*DB) BindArrowIPC

func (db *DB) BindArrowIPC(logical string, ipc []byte) error

BindArrowIPC binds Arrow IPC file bytes under a logical table name.

Example
package main

import (
	"fmt"
	"log"

	velr "github.com/velr-ai/velr-go-driver"
)

func main() {
	db, err := velr.OpenInMemory()
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	var ipcFileBytes []byte
	if err := db.BindArrowIPC("people", ipcFileBytes); err != nil {
		log.Fatal(err)
	}

	rows, err := db.Query("UNWIND BIND('people') AS row RETURN row.name AS name")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(rows)
}

func (*DB) Close

func (db *DB) Close() error

Close closes the database connection. It is safe to call more than once.

func (*DB) CurrentSchemaVersion

func (db *DB) CurrentSchemaVersion() (int, error)

CurrentSchemaVersion returns the schema version supported by the runtime.

func (*DB) Exec

func (db *DB) Exec(cypher string, options ...QueryOptions) (*Stream, error)

Exec executes Cypher and returns a stream of result tables.

func (*DB) ExecOne

func (db *DB) ExecOne(cypher string, options ...QueryOptions) (*Table, error)

ExecOne executes Cypher and requires exactly one result table.

func (*DB) ExecOneWithParams

func (db *DB) ExecOneWithParams(cypher string, params Params) (*Table, error)

ExecOneWithParams executes Cypher with named parameters and requires exactly one result table.

func (*DB) ExecWithParams

func (db *DB) ExecWithParams(cypher string, params Params) (*Stream, error)

ExecWithParams executes Cypher with named parameters.

func (*DB) Explain

func (db *DB) Explain(cypher string) (*ExplainTrace, error)

Explain builds an explain trace without executing the query.

Example
package main

import (
	"fmt"
	"log"

	velr "github.com/velr-ai/velr-go-driver"
)

func main() {
	db, err := velr.OpenInMemory()
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	trace, err := db.Explain("MATCH (p:Person) RETURN p.name")
	if err != nil {
		log.Fatal(err)
	}
	defer trace.Close()

	text, err := trace.CompactString()
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(text)
}

func (*DB) ExplainAnalyze

func (db *DB) ExplainAnalyze(cypher string) (*ExplainTrace, error)

ExplainAnalyze executes the query and returns an analyzed explain trace.

func (*DB) Migrate

func (db *DB) Migrate() (MigrationReport, error)

Migrate explicitly migrates the opened database to the current schema.

func (*DB) NeedsMigration

func (db *DB) NeedsMigration() (bool, error)

NeedsMigration reports whether the opened database is older than the runtime schema.

func (*DB) Query

func (db *DB) Query(cypher string, options ...QueryOptions) ([]map[string]any, error)

Query executes Cypher and converts the single result table to row objects.

func (*DB) QueryWithParams

func (db *DB) QueryWithParams(cypher string, params Params) ([]map[string]any, error)

QueryWithParams executes Cypher with named parameters and returns row objects.

func (*DB) RegisterVectorEmbedder

func (db *DB) RegisterVectorEmbedder(name string, embedder VectorEmbedder) error

RegisterVectorEmbedder registers or replaces a named vector embedding callback.

Vector indexes refer to this name with OPTIONS { indexConfig: { embedder: 'name' } }. The callback is invoked synchronously by the native runtime, so it must not perform asynchronous work.

Example
package main

import (
	"log"

	velr "github.com/velr-ai/velr-go-driver"
)

func main() {
	db, err := velr.OpenInMemory()
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	err = db.RegisterVectorEmbedder("demo", func(inputs []velr.VectorEmbeddingInput) ([][]float32, error) {
		vectors := make([][]float32, len(inputs))
		for i, input := range inputs {
			vector := make([]float32, input.Dimensions)
			if input.Text() != "" && len(vector) > 0 {
				vector[0] = 1
			}
			vectors[i] = vector
		}
		return vectors, nil
	})
	if err != nil {
		log.Fatal(err)
	}

	err = db.Run(`
		CREATE (:Paper {title: 'Graph retrieval'})
		CREATE VECTOR INDEX paperEmbedding IF NOT EXISTS
		FOR (p:Paper) ON EACH [p.title]
		OPTIONS {indexConfig: {dimensions: 3, embedder: 'demo'}}
	`)
	if err != nil {
		log.Fatal(err)
	}
}

func (*DB) Run

func (db *DB) Run(cypher string, options ...QueryOptions) error

Run executes Cypher and discards all result tables.

func (*DB) RunWithParams

func (db *DB) RunWithParams(cypher string, params Params) error

RunWithParams executes Cypher with named parameters and discards result tables.

func (*DB) SchemaVersion

func (db *DB) SchemaVersion() (int, error)

SchemaVersion returns the schema version of the opened database.

func (*DB) Transaction

func (db *DB) Transaction(fn func(*Tx) error) error

Transaction runs fn inside a transaction, committing on nil error and rolling back otherwise.

Example
package main

import (
	"log"

	velr "github.com/velr-ai/velr-go-driver"
)

func main() {
	db, err := velr.OpenInMemory()
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	err = db.Transaction(func(tx *velr.Tx) error {
		if err := tx.Run("CREATE (:Account {name: 'checking', balance: 100})"); err != nil {
			return err
		}
		return tx.Run("CREATE (:Account {name: 'savings', balance: 50})")
	})
	if err != nil {
		log.Fatal(err)
	}
}

type Error

type Error struct {
	// Code is the numeric status code returned by the native runtime.
	Code int

	// Message is the human-readable error message returned by the runtime or driver.
	Message string
}

Error is returned by Velr runtime and driver operations.

func (*Error) Error

func (e *Error) Error() string

Error returns the formatted Velr error message.

type ExplainPlan

type ExplainPlan struct {
	// Meta contains plan metadata copied from the trace.
	Meta ExplainPlanMeta

	// Steps contains the ordered explain steps in the plan.
	Steps []ExplainStep
}

ExplainPlan is an owned explain plan snapshot.

type ExplainPlanMeta

type ExplainPlanMeta struct {
	// PlanID is the runtime identifier for the plan.
	PlanID string

	// Cypher is the Cypher statement represented by the plan.
	Cypher string

	// StepCount is the number of explain steps in the plan.
	StepCount int
}

ExplainPlanMeta describes one explain plan.

type ExplainStatement

type ExplainStatement struct {
	// Meta contains statement metadata copied from the trace.
	Meta ExplainStatementMeta

	// SQLitePlanDetails contains SQLite EXPLAIN QUERY PLAN detail strings.
	SQLitePlanDetails []string
}

ExplainStatement is an owned explain statement snapshot.

type ExplainStatementMeta

type ExplainStatementMeta struct {
	// StatementID is the runtime identifier for the SQL statement.
	StatementID string

	// Kind describes the statement category.
	Kind string

	// SQL is the SQL text emitted for this explain statement.
	SQL string

	// Note contains optional extra detail for this statement.
	Note *string

	// SQLitePlanCount is the number of SQLite plan details for this statement.
	SQLitePlanCount int
}

ExplainStatementMeta describes one explain statement.

type ExplainStep

type ExplainStep struct {
	// Meta contains step metadata copied from the trace.
	Meta ExplainStepMeta

	// Statements contains SQL statements attached to the step.
	Statements []ExplainStatement
}

ExplainStep is an owned explain step snapshot.

type ExplainStepMeta

type ExplainStepMeta struct {
	// StepNo is the step number within the plan.
	StepNo int

	// GroupID identifies the logical operation group when one is available.
	GroupID string

	// OpIndex identifies the operation index inside the plan.
	OpIndex string

	// Phase describes the planning or execution phase for this step.
	Phase string

	// Title is the human-readable step title.
	Title string

	// Source identifies the Velr planner or runtime source for this step.
	Source string

	// Note contains optional extra detail for this step.
	Note *string

	// StatementCount is the number of SQL statements attached to this step.
	StatementCount int
}

ExplainStepMeta describes one explain step.

type ExplainTrace

type ExplainTrace struct {
	// contains filtered or unexported fields
}

ExplainTrace is an EXPLAIN or EXPLAIN ANALYZE result.

func (*ExplainTrace) Close

func (x *ExplainTrace) Close() error

Close releases the trace. It is safe to call more than once.

func (*ExplainTrace) CompactBytes

func (x *ExplainTrace) CompactBytes() ([]byte, error)

CompactBytes renders the trace in Velr's compact text form.

func (*ExplainTrace) CompactLen

func (x *ExplainTrace) CompactLen() (int, error)

CompactLen returns the byte length of the compact text rendering.

func (*ExplainTrace) CompactString

func (x *ExplainTrace) CompactString() (string, error)

CompactString renders the trace in Velr's compact text form.

func (*ExplainTrace) PlanCount

func (x *ExplainTrace) PlanCount() (int, error)

PlanCount returns the number of plans in the trace.

func (*ExplainTrace) PlanMeta

func (x *ExplainTrace) PlanMeta(planIdx int) (ExplainPlanMeta, error)

PlanMeta returns metadata for one plan.

func (*ExplainTrace) SQLitePlanCount

func (x *ExplainTrace) SQLitePlanCount(planIdx, stepIdx, stmtIdx int) (int, error)

SQLitePlanCount returns the number of SQLite plan details for a statement.

func (*ExplainTrace) SQLitePlanDetail

func (x *ExplainTrace) SQLitePlanDetail(planIdx, stepIdx, stmtIdx, detailIdx int) (string, error)

SQLitePlanDetail returns one SQLite plan detail string.

func (*ExplainTrace) SQLitePlanDetails

func (x *ExplainTrace) SQLitePlanDetails(planIdx, stepIdx, stmtIdx int) ([]string, error)

SQLitePlanDetails returns all SQLite plan detail strings for a statement.

func (*ExplainTrace) Snapshot

func (x *ExplainTrace) Snapshot() ([]ExplainPlan, error)

Snapshot materializes the trace into owned Go structs.

func (*ExplainTrace) StatementCount

func (x *ExplainTrace) StatementCount(planIdx, stepIdx int) (int, error)

StatementCount returns the number of statements in one step.

func (*ExplainTrace) StatementMeta

func (x *ExplainTrace) StatementMeta(planIdx, stepIdx, stmtIdx int) (ExplainStatementMeta, error)

StatementMeta returns metadata for one explain statement.

func (*ExplainTrace) StepCount

func (x *ExplainTrace) StepCount(planIdx int) (int, error)

StepCount returns the number of steps in one plan.

func (*ExplainTrace) StepMeta

func (x *ExplainTrace) StepMeta(planIdx, stepIdx int) (ExplainStepMeta, error)

StepMeta returns metadata for one explain step.

func (*ExplainTrace) WriteCompact

func (x *ExplainTrace) WriteCompact(w io.Writer) (int64, error)

WriteCompact writes the compact text rendering to w.

type GeoJSON

type GeoJSON struct {
	// Type is the GeoJSON geometry type, such as Point or GeometryCollection.
	Type string

	// Coordinates contains the GeoJSON coordinates for non-collection values.
	Coordinates any

	// Geometries contains nested geometries for GeometryCollection values.
	Geometries []GeoJSON

	// Raw contains the decoded canonical GeoJSON object.
	Raw map[string]any
}

GeoJSON is a spatial value represented in Velr's canonical JSON form.

type MigrationReport

type MigrationReport struct {
	// FromVersion is the schema version before migration.
	FromVersion int

	// ToVersion is the schema version after migration.
	ToVersion int

	// Status reports whether migration work was performed.
	Status MigrationStatus

	// Steps lists migration steps reported by the runtime.
	Steps []string
}

MigrationReport describes a schema migration operation.

type MigrationStatus

type MigrationStatus string

MigrationStatus is returned by Migrate.

const (
	// MigrationAlreadyCurrent means no schema migration was needed.
	MigrationAlreadyCurrent MigrationStatus = "already_current"

	// MigrationMigrated means the database was migrated to the current schema.
	MigrationMigrated MigrationStatus = "migrated"
)

type Node

type Node struct {
	// Identity is the runtime-local numeric node identifier.
	Identity int64

	// ElementID is the stable textual node identifier exposed by Cypher.
	ElementID string

	// Labels contains the node labels in database order.
	Labels []string

	// Properties contains decoded node properties keyed by property name.
	Properties map[string]PropertyValue
}

Node is a decoded Velr graph node value.

type Params

type Params map[string]any

Params is a map of named Cypher parameters.

Query text references parameters as $name; map keys omit the leading $.

type Path

type Path struct {
	// Elements alternates node and relationship entries in path order.
	Elements []PathElement
}

Path is a decoded Velr graph path.

func (Path) Nodes

func (p Path) Nodes() []Node

Nodes returns the node elements in path order.

func (Path) Relationships

func (p Path) Relationships() []Relationship

Relationships returns the relationship elements in path order.

type PathElement

type PathElement struct {
	// Node is populated when this path element is a node.
	Node *Node

	// Relationship is populated when this path element is a relationship.
	Relationship *Relationship
}

PathElement is one node or relationship in a decoded path.

type PropertyValue

type PropertyValue struct {
	// Type identifies which value field is populated.
	Type PropertyValueType

	// Bool is set when Type is PropertyBool.
	Bool bool

	// Int64 is set when Type is PropertyInt64.
	Int64 int64

	// Float64 is set when Type is PropertyDouble.
	Float64 float64

	// Text is set for string, temporal, and duration values.
	Text string

	// List is set when Type is PropertyList.
	List []PropertyValue

	// Vector is set when Type is PropertyVector.
	Vector []float64

	// Bytes is set when Type is PropertyBytes.
	Bytes []byte

	// GeoJSON is set for spatial point, geometry, and geography values.
	GeoJSON *GeoJSON

	// Display is Velr's canonical display rendering when one is available.
	Display string
}

PropertyValue is a typed Velr property value.

Temporal values are exposed in their canonical openCypher text form. Spatial values are exposed as GeoJSON. Use GoValue when a plain Go representation is more convenient than switching on Type.

func (PropertyValue) GoValue

func (v PropertyValue) GoValue() any

GoValue converts the value to an idiomatic Go representation.

func (PropertyValue) Kind

Kind returns the Velr property value kind.

func (PropertyValue) String

func (v PropertyValue) String() string

String returns Velr's display text when available, otherwise a Go rendering.

type PropertyValueType

type PropertyValueType int

PropertyValueType describes the public Velr property value kind.

const (
	// PropertyNull is a null property value.
	PropertyNull PropertyValueType = iota

	// PropertyBool is a boolean property value.
	PropertyBool

	// PropertyInt64 is a signed 64-bit integer property value.
	PropertyInt64

	// PropertyDouble is a floating-point property value.
	PropertyDouble

	// PropertyString is a string property value.
	PropertyString

	// PropertyDate is a date property value in canonical openCypher text form.
	PropertyDate

	// PropertyLocalTime is a local time property value in canonical openCypher text form.
	PropertyLocalTime

	// PropertyZonedTime is a zoned time property value in canonical openCypher text form.
	PropertyZonedTime

	// PropertyLocalDateTime is a local datetime property value in canonical openCypher text form.
	PropertyLocalDateTime

	// PropertyZonedDateTime is a zoned datetime property value in canonical openCypher text form.
	PropertyZonedDateTime

	// PropertyDuration is a duration property value in canonical openCypher text form.
	PropertyDuration

	// PropertyPoint is a point property value represented as GeoJSON.
	PropertyPoint

	// PropertyGeometry is a geometry property value represented as GeoJSON.
	PropertyGeometry

	// PropertyGeography is a geography property value represented as GeoJSON.
	PropertyGeography

	// PropertyList is a list property value.
	PropertyList

	// PropertyVector is a numeric vector property value.
	PropertyVector

	// PropertyBytes is a byte-array property value.
	PropertyBytes
)

func (PropertyValueType) String

func (t PropertyValueType) String() string

String returns the stable text form of t.

type QueryOptions

type QueryOptions struct {
	// HasMaxResultRows reports whether MaxResultRows should be applied.
	HasMaxResultRows bool

	// MaxResultRows caps emitted rows per result table when HasMaxResultRows is true.
	MaxResultRows int

	// Params contains named Cypher parameters for this query.
	Params Params
}

QueryOptions configures query execution.

func MaxResultRows

func MaxResultRows(n int) QueryOptions

MaxResultRows creates QueryOptions that cap emitted rows per result table.

func WithParams

func WithParams(params Params) QueryOptions

WithParams creates QueryOptions with named query parameters.

func (QueryOptions) WithMaxResultRows

func (opts QueryOptions) WithMaxResultRows(n int) QueryOptions

WithMaxResultRows returns a copy of opts with a row cap set.

func (QueryOptions) WithParam

func (opts QueryOptions) WithParam(name string, value any) QueryOptions

WithParam returns a copy of opts with one parameter set.

func (QueryOptions) WithParams

func (opts QueryOptions) WithParams(params Params) QueryOptions

WithParams returns a copy of opts with named query parameters set.

type Relationship

type Relationship struct {
	// Identity is the runtime-local numeric relationship identifier.
	Identity int64

	// ElementID is the stable textual relationship identifier exposed by Cypher.
	ElementID string

	// Type is the relationship type.
	Type string

	// Start is the runtime-local numeric identifier of the start node.
	Start int64

	// End is the runtime-local numeric identifier of the end node.
	End int64

	// StartElementID is the stable textual identifier of the start node.
	StartElementID string

	// EndElementID is the stable textual identifier of the end node.
	EndElementID string

	// Properties contains decoded relationship properties keyed by property name.
	Properties map[string]PropertyValue
}

Relationship is a decoded Velr graph relationship value.

type Rows

type Rows struct {
	// contains filtered or unexported fields
}

Rows is a streaming row cursor.

func (*Rows) Close

func (r *Rows) Close() error

Close releases the row cursor. It is safe to call more than once.

func (*Rows) Next

func (r *Rows) Next() ([]Cell, error)

Next returns the next row, or nil at EOF.

func (*Rows) NextInto

func (r *Rows) NextInto(dest ...any) (bool, error)

NextInto scans the next row into destination pointers.

It returns false at EOF. The number of destinations must match the row width.

Example
package main

import (
	"fmt"
	"log"

	velr "github.com/velr-ai/velr-go-driver"
)

func main() {
	db, err := velr.OpenInMemory()
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	table, err := db.ExecOne("RETURN 42 AS answer, 'Velr' AS name")
	if err != nil {
		log.Fatal(err)
	}
	defer table.Close()

	rows, err := table.Rows()
	if err != nil {
		log.Fatal(err)
	}
	defer rows.Close()

	var answer int64
	var name string
	ok, err := rows.NextInto(&answer, &name)
	if err != nil {
		log.Fatal(err)
	}
	if ok {
		fmt.Println(answer, name)
	}
}

type Savepoint

type Savepoint struct {
	// contains filtered or unexported fields
}

Savepoint is a transaction savepoint handle.

func (*Savepoint) Close

func (sp *Savepoint) Close() error

Close releases the native savepoint handle without an explicit release or rollback.

If the savepoint is still active, the native runtime rolls back to it and releases it.

func (*Savepoint) Release

func (sp *Savepoint) Release() error

Release releases the savepoint. The savepoint is consumed.

func (*Savepoint) Rollback

func (sp *Savepoint) Rollback() error

Rollback rolls back to the savepoint and releases it. The savepoint is consumed.

type StorageValueType

type StorageValueType int

StorageValueType describes the storage class used to reconstruct a Velr value.

const (
	// StorageNull means the original storage value was null.
	StorageNull StorageValueType = iota

	// StorageInt64 means the original storage value was a signed 64-bit integer.
	StorageInt64

	// StorageDouble means the original storage value was a floating-point number.
	StorageDouble

	// StorageText means the original storage value was text.
	StorageText

	// StorageBlob means the original storage value was bytes.
	StorageBlob
)

func (StorageValueType) String

func (t StorageValueType) String() string

String returns the stable text form of t.

type Stream

type Stream struct {
	// contains filtered or unexported fields
}

Stream is a streaming query result.

func (*Stream) Close

func (s *Stream) Close() error

Close releases the stream. It is safe to call more than once.

func (*Stream) NextTable

func (s *Stream) NextTable() (*Table, error)

NextTable returns the next table, or nil when the stream is exhausted.

type Table

type Table struct {
	// contains filtered or unexported fields
}

Table is one result table.

func (*Table) Close

func (t *Table) Close() error

Close releases the table. It is safe to call more than once.

func (*Table) Collect

func (t *Table) Collect() ([][]Cell, error)

Collect returns every row as cells.

func (*Table) ColumnCount

func (t *Table) ColumnCount() (int, error)

ColumnCount returns the number of result columns.

func (*Table) ColumnNames

func (t *Table) ColumnNames() ([]string, error)

ColumnNames returns result column names.

func (*Table) ForEachRow

func (t *Table) ForEachRow(fn func([]Cell) error) error

ForEachRow visits every row and closes the row cursor afterwards.

func (*Table) Rows

func (t *Table) Rows() (*Rows, error)

Rows opens a streaming row cursor for the table.

func (*Table) ToArrowIPC

func (t *Table) ToArrowIPC() ([]byte, error)

ToArrowIPC exports the table as Arrow IPC file bytes.

func (*Table) ToObjects

func (t *Table) ToObjects() ([]map[string]any, error)

ToObjects converts all rows to maps keyed by column name.

type Tx

type Tx struct {
	// contains filtered or unexported fields
}

Tx is an explicit Velr transaction.

func (*Tx) BindArrow

func (tx *Tx) BindArrow(logical string, columns []ArrowColumn) error

BindArrow binds Arrow C Data Interface columns inside the transaction.

func (*Tx) BindArrowChunks

func (tx *Tx) BindArrowChunks(logical string, columns []ArrowColumnChunks) error

BindArrowChunks binds chunked Arrow C Data Interface columns inside the transaction.

func (*Tx) BindArrowIPC

func (tx *Tx) BindArrowIPC(logical string, ipc []byte) error

BindArrowIPC binds Arrow IPC file bytes under a logical table name inside the transaction.

func (*Tx) Close

func (tx *Tx) Close() error

Close rolls back an uncommitted transaction. It is safe to call more than once.

func (*Tx) Commit

func (tx *Tx) Commit() error

Commit commits the transaction. The transaction is consumed.

func (*Tx) Exec

func (tx *Tx) Exec(cypher string, options ...QueryOptions) (*TxStream, error)

Exec executes Cypher inside the transaction.

func (*Tx) ExecOne

func (tx *Tx) ExecOne(cypher string, options ...QueryOptions) (*Table, error)

ExecOne executes Cypher inside the transaction and requires exactly one table.

func (*Tx) ExecOneWithParams

func (tx *Tx) ExecOneWithParams(cypher string, params Params) (*Table, error)

ExecOneWithParams executes Cypher with named parameters and requires exactly one table.

func (*Tx) ExecWithParams

func (tx *Tx) ExecWithParams(cypher string, params Params) (*TxStream, error)

ExecWithParams executes Cypher inside the transaction with named parameters.

func (*Tx) Explain

func (tx *Tx) Explain(cypher string) (*ExplainTrace, error)

Explain builds an explain trace inside the transaction.

func (*Tx) ExplainAnalyze

func (tx *Tx) ExplainAnalyze(cypher string) (*ExplainTrace, error)

ExplainAnalyze executes the query in the transaction and returns an analyzed explain trace.

func (*Tx) Query

func (tx *Tx) Query(cypher string, options ...QueryOptions) ([]map[string]any, error)

Query executes Cypher inside the transaction and converts the single table to objects.

func (*Tx) QueryWithParams

func (tx *Tx) QueryWithParams(cypher string, params Params) ([]map[string]any, error)

QueryWithParams executes Cypher with named parameters and returns row objects.

func (*Tx) ReleaseSavepoint

func (tx *Tx) ReleaseSavepoint(name string) error

ReleaseSavepoint releases the most recently created active named savepoint.

func (*Tx) Rollback

func (tx *Tx) Rollback() error

Rollback rolls back the transaction. The transaction is consumed.

func (*Tx) RollbackTo

func (tx *Tx) RollbackTo(name string) error

RollbackTo rolls back to a named savepoint and keeps that savepoint active.

func (*Tx) Run

func (tx *Tx) Run(cypher string, options ...QueryOptions) error

Run executes Cypher inside the transaction and discards result tables.

func (*Tx) RunWithParams

func (tx *Tx) RunWithParams(cypher string, params Params) error

RunWithParams executes Cypher inside the transaction with named parameters.

func (*Tx) Savepoint

func (tx *Tx) Savepoint() (*Savepoint, error)

Savepoint creates an unnamed scoped savepoint.

Example
package main

import (
	"log"

	velr "github.com/velr-ai/velr-go-driver"
)

func main() {
	db, err := velr.OpenInMemory()
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	tx, err := db.BeginTx()
	if err != nil {
		log.Fatal(err)
	}
	defer tx.Close()

	if err := tx.Run("CREATE (:Item {name: 'kept'})"); err != nil {
		log.Fatal(err)
	}
	sp, err := tx.Savepoint()
	if err != nil {
		log.Fatal(err)
	}
	if err := tx.Run("CREATE (:Item {name: 'discarded'})"); err != nil {
		log.Fatal(err)
	}
	if err := sp.Rollback(); err != nil {
		log.Fatal(err)
	}
	if err := tx.Commit(); err != nil {
		log.Fatal(err)
	}
}

func (*Tx) SavepointNamed

func (tx *Tx) SavepointNamed(name string) (*Savepoint, error)

SavepointNamed creates a named transaction-owned savepoint.

type TxStream

type TxStream struct {
	// contains filtered or unexported fields
}

TxStream is a streaming query result inside a transaction.

func (*TxStream) Close

func (s *TxStream) Close() error

Close releases the transaction stream. It is safe to call more than once.

func (*TxStream) NextTable

func (s *TxStream) NextTable() (*Table, error)

NextTable returns the next table, or nil when the stream is exhausted.

type VectorEmbedder

type VectorEmbedder func(inputs []VectorEmbeddingInput) ([][]float32, error)

VectorEmbedder is a synchronous embedding callback used by vector indexes.

It receives a batch of inputs and must return one vector per input. Every vector must have input.Dimensions finite float32 values.

type VectorEmbeddingField

type VectorEmbeddingField struct {
	// Name is the source field or property name when Velr supplied one.
	Name string

	// HasName reports whether Name was supplied by the runtime.
	HasName bool

	// Value is the decoded typed property value for this field.
	Value PropertyValue

	// StorageType is the original low-level storage class of the field.
	StorageType StorageValueType

	// RawStorage contains the runtime's raw storage bytes when exposed by the ABI.
	RawStorage []byte

	// RawJSON contains the canonical JSON bytes used to decode Value when present.
	RawJSON []byte

	// Display contains Velr's display rendering for the field.
	Display string
}

VectorEmbeddingField is one value passed to a vector embedder.

func (VectorEmbeddingField) GoValue

func (f VectorEmbeddingField) GoValue() any

GoValue returns an idiomatic Go rendering of the field value.

type VectorEmbeddingInput

type VectorEmbeddingInput struct {
	// IndexName is the vector index requesting embeddings.
	IndexName string

	// Dimensions is the exact number of float32 values the callback must return per input.
	Dimensions int

	// Purpose explains whether Velr is indexing data or embedding a query.
	Purpose VectorEmbeddingPurpose

	// EntityKind identifies the graph entity kind when HasEntity is true.
	EntityKind VectorEntityKind

	// EntityID is the runtime-local graph entity identifier when HasEntity is true.
	EntityID int64

	// HasEntity reports whether EntityKind and EntityID refer to a graph entity.
	HasEntity bool

	// Fields contains the source values Velr wants embedded.
	Fields []VectorEmbeddingField
}

VectorEmbeddingInput is one source row passed to a vector embedder.

func (VectorEmbeddingInput) Text

func (in VectorEmbeddingInput) Text() string

Text joins the display rendering of all fields and is useful for simple text embedders.

type VectorEmbeddingPurpose

type VectorEmbeddingPurpose int

VectorEmbeddingPurpose explains why Velr is asking for embeddings.

const (
	// VectorEmbeddingIndexEntity requests embeddings for graph entities being indexed.
	VectorEmbeddingIndexEntity VectorEmbeddingPurpose = iota

	// VectorEmbeddingQuery requests embeddings for a vector search query.
	VectorEmbeddingQuery
)

func (VectorEmbeddingPurpose) String

func (p VectorEmbeddingPurpose) String() string

String returns the stable text form of p.

type VectorEntityKind

type VectorEntityKind int

VectorEntityKind identifies the graph entity kind being indexed.

const (
	// VectorEntityNone means the embedding input is not tied to a graph entity.
	VectorEntityNone VectorEntityKind = iota

	// VectorEntityNode means the embedding input describes a node.
	VectorEntityNode

	// VectorEntityRelationship means the embedding input describes a relationship.
	VectorEntityRelationship
)

func (VectorEntityKind) String

func (k VectorEntityKind) String() string

String returns the stable text form of k.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL