An Ecto.Type for mapping TiDB VECTOR columns to %TiDB.Vector{} structs.
This module allows Ecto schemas to seamlessly work with TiDB vector columns,
automatically casting inputs (such as lists of numbers or Nx tensors) into
%TiDB.Vector{} structs and converting them to/from TiDB SQL formats when
persisting or loading from the database.
Usage in Schemas
Add the field to your schema with the TiDB.Ecto.Vector type:
defmodule MyApp.Document do
use Ecto.Schema
import Ecto.Changeset
schema "documents" do
field :title, :string
field :embedding, TiDB.Ecto.Vector
timestamps()
end
def changeset(doc, attrs) do
doc
|> cast(attrs, [:title, :embedding])
|> validate_required([:title, :embedding])
end
endCasting Behavior
cast/1 accepts:
- An existing
%TiDB.Vector{}struct. - A list of numbers (e.g.
[0.1, 0.2, 0.3]or[1, 2, 3]). - A JSON string representation of a number array (e.g.
"[0.1, 0.2, 0.3]"). - An
Nx.Tensorstruct with rank 1 (when:nxis loaded).
Returns {:ok, %TiDB.Vector{}} on success or :error for invalid inputs.
Summary
Functions
Casts a value to a %TiDB.Vector{} struct.
Dumps a %TiDB.Vector{} struct or number list into its database SQL string representation.
Callback implementation for Ecto.Type.embed_as/1.
Callback implementation for Ecto.Type.equal?/2.
Loads a vector value from the database format (JSON string literal) into a %TiDB.Vector{}.
Returns the underlying database type identifier :vector.
Types
@type t() :: TiDB.Vector.t()
The underlying Elixir vector struct representation.
Functions
@spec cast(term()) :: {:ok, TiDB.Vector.t()} | :error
Casts a value to a %TiDB.Vector{} struct.
Accepts lists of numbers, strings, vectors, or 1D Nx tensors.
Examples
iex> TiDB.Ecto.Vector.cast([1.0, 2.0])
{:ok, TiDB.Vector.new([1.0, 2.0])}
iex> TiDB.Ecto.Vector.cast("invalid")
:error
Dumps a %TiDB.Vector{} struct or number list into its database SQL string representation.
Examples
iex> vec = TiDB.Vector.new([1.0, 2.0])
iex> TiDB.Ecto.Vector.dump(vec)
{:ok, "[1.0,2.0]"}
iex> TiDB.Ecto.Vector.dump([1.0, 2.0])
{:ok, "[1.0,2.0]"}
iex> TiDB.Ecto.Vector.dump(:invalid)
:error
Callback implementation for Ecto.Type.embed_as/1.
Callback implementation for Ecto.Type.equal?/2.
@spec load(term()) :: {:ok, TiDB.Vector.t()} | :error
Loads a vector value from the database format (JSON string literal) into a %TiDB.Vector{}.
Examples
iex> TiDB.Ecto.Vector.load("[1.0, 2.0]")
{:ok, TiDB.Vector.new([1.0, 2.0])}
iex> TiDB.Ecto.Vector.load("not_valid_json")
:error
@spec type() :: :vector
Returns the underlying database type identifier :vector.