Skip to content

TypeScript API reference

Everything below is exported from the lance-csr npm package. The classes are thin TypeScript wrappers around the Rust engine, and this page is generated from their TSDoc comments and types, so it matches the package. Using from TypeScript has worked examples and a table that maps each Python class and method to its TypeScript counterpart.

Export Purpose
GraphConfig, GraphConfigBuilder Map tables to node labels and relationship types
CypherEngine Run many Cypher queries over registered datasets
CypherQuery Run one Cypher query
RecordBatchStream Read a result one batch at a time
SqlEngine, SqlQuery Run SQL through DataFusion
VectorSearch, DistanceMetric Vector similarity search and reranking
DirNamespace Resolve table names to Lance datasets in a directory
LanceCsrError The error the engine throws, with a code
ExecutionStrategy, SqlDialect Enums

version is the package version. Datasets are apache-arrow Tables and RecordBatches, or Lance datasets given as LanceDataset objects, and results are apache-arrow tables.

This page covers the TypeScript API. Python users should read the Python API reference, and Rust users the Rust API reference on docs.rs.

Classes

CypherEngine

Run many Cypher queries over the same datasets.

The engine registers datasets once and reuses the catalog, the DataFusion session and (with useCsr) the CSR index across queries. Queries can run concurrently.

Lance datasets are read lazily, pinned to the version given (the latest when left out): later writes, by this or another process, aren't visible until CypherEngine.checkoutLatest. Each dataset is pinned separately, so versions across tables are not a transactional snapshot. Arrow inputs are held in memory and never change; create a new engine to replace them.

execute and executeBatches reuse up to 128 unoptimized query templates per snapshot, keyed by the exact query text and the names and types of scalar parameters. Values are bound before optimization on every call. A successful checkoutLatest clears the cache. See Repeated queries.

Example

TypeScript
import { tableFromArrays } from "apache-arrow";
import { CypherEngine, GraphConfig } from "lance-csr";

const config = GraphConfig.builder()
  .nodeTable("Person", "id")
  .relTable("KNOWS", "Person", "Person", "src_id", "dst_id")
  .build();
const engine = await CypherEngine.create(config, {
  Person: tableFromArrays({ id: Int32Array.from([1, 2]), name: ["Alice", "Bob"] }),
  KNOWS: tableFromArrays({ src_id: Int32Array.from([1]), dst_id: Int32Array.from([2]) }),
});
const result = await engine.execute(
  "MATCH (a:Person)-[:KNOWS]->(b:Person) RETURN a.name, b.name",
);
result.toArray().map((row) => row.toJSON()); // [{ "a.name": "Alice", "b.name": "Bob" }]

Methods

checkoutLatest()
TypeScript
checkoutLatest(): Promise<void>;

Move every Lance dataset to its latest version.

Updates the CSR, node indexes and statistics to match. Datasets whose version and commit time are unchanged keep their open handle. The replacement is validated in full before it's swapped in: on error nothing changes and the previous snapshot stays usable. Queries already running finish on the snapshot they started with. Arrow inputs are unchanged. Concurrent calls run one at a time, and targetPartitions is preserved. See Lance datasets.

Returns

Promise\<void>

config()
TypeScript
config(): GraphConfig;

The engine's graph config.

Returns

GraphConfig

csrStats()
TypeScript
csrStats(): Record<string, CsrStats>;

Statistics for each CSR adjacency index (experimental; needs useCsr), keyed by relationship type; empty without useCsr. An identical result after checkoutLatest means the snapshot itself didn't change. See Inspecting the CSR.

Returns

Record\<string, CsrStats>

datasetVersions()
TypeScript
datasetVersions(): Record<string, number>;

The pinned version of each Lance dataset, keyed by dataset name. Arrow inputs aren't listed.

Returns

Record\<string, number>

deleteStoredCsr()
TypeScript
deleteStoredCsr(): Promise<number>;

Delete the CSR files stored with persistCsr (experimental).

Removes the _lance_csr folder of every Lance relationship dataset this engine reads. The engine keeps the CSR it already holds in memory, so queries aren't affected. See Storing the CSR.

Returns

Promise\<number>

The number of files deleted; 0 when nothing was stored.

Throws

LanceCsrError InvalidArgument if the engine was created with persistCsr: "load", which never writes to its datasets.

execute()
TypeScript
execute(
   query, 
   params?, 
   options?
): Promise<Table<any>>;

Run a Cypher query and return the whole result.

The result is held in memory; use CypherEngine.executeBatches for large outputs.

Parameters
Parameter Type Description
query string The Cypher query.
params? Record\<string, Parameter> | null Values for $name parameters; see Parameter.
options? ExecuteOptions timeoutMs: milliseconds for the whole query.
Returns

Promise\<Table\<any>>

The query result.

Throws

LanceCsrError with code InvalidArgument if the query is invalid, refers to an unknown label, compares or combines incompatible types, or a parameter is unsupported, nested beyond 128 levels or cyclic; NotImplemented if the query uses a Cypher feature that parses but isn't supported; Timeout if it runs past timeoutMs; Runtime if execution fails.

executeBatches()
TypeScript
executeBatches(
   query, 
   params?, 
   options?
): Promise<RecordBatchStream>;

Run a Cypher query and stream the result.

Planning errors reject the returned promise; execution errors reject while reading.

Parameters
Parameter Type Description
query string The Cypher query.
params? Record\<string, Parameter> | null Values for $name parameters, as for CypherEngine.execute.
options? ExecuteOptions timeoutMs: milliseconds for the whole query, including pauses between reads.
Returns

Promise\<RecordBatchStream>

The result, one batch at a time.

executeWithVectorRerank()
TypeScript
executeWithVectorRerank(query, vectorSearch): Promise<Table<any>>;

Run a Cypher query, then rank its rows by vector similarity.

Parameters
Parameter Type Description
query string The Cypher query. It must return the column vectorSearch ranks by.
vectorSearch VectorSearch The ranking.
Returns

Promise\<Table\<any>>

At most topK rows, closest first.

explain()
TypeScript
explain(
   query, 
   params?, 
   options?
): Promise<string>;

The plans for a query, without running it unless analyze is set.

Parameters
Parameter Type Description
query string The Cypher query.
params? Record\<string, Parameter> | null Values for $name parameters, as for CypherEngine.execute.
options? ExplainOptions analyze: run the query and show each operator's metrics.
Returns

Promise\<string>

The graph logical plan, the DataFusion logical plan and the physical plan, including pushed-down scans. With analyze, the physical plan's row is labelled physical_plan_with_metrics.

exportGraph()
TypeScript
exportGraph(relTypes?, options?): Promise<GraphExport>;

The whole graph as typed arrays over dense node ids, for drawing it in a browser.

Nodes are numbered 0 to numNodes - 1 and each edge is a pair of those numbers, the form GPU graph renderers take. Reads the key column of each node table and the endpoint columns of each relationship table from the engine's pinned snapshot, as queries see it, with or without useCsr. Lance datasets are scanned for just those columns. See Drawing the whole graph.

Parameters
Parameter Type Description
relTypes? string[] Relationship types to include, case-insensitive. Left out, every type whose dataset has integer endpoint columns. The nodes are those of the labels at either end of the included types.
options? { directed?: boolean; } -
options.directed? boolean true (the default) returns out-edge and in-edge arrays; false returns one set of arrays listing every edge in both directions.
Returns

Promise\<GraphExport>

Throws

LanceCsrError InvalidArgument if a relationship type or label isn't in the config, has no dataset, or a key or endpoint column is missing or isn't an integer type up to int64, or there's nothing to export; Runtime if a node key appears twice within a label, or a scan fails.

nodeIndexStats()
TypeScript
nodeIndexStats(): Record<string, NodeIndexStats>;

Statistics for each node index (experimental; needs useCsr).

A label is missing when its keys aren't unique integers; relationships that end at it then use a join.

Returns

Record\<string, NodeIndexStats>

optimizeCsr()
TypeScript
optimizeCsr(): Promise<void>;

Rebuild each CSR that carries a delta (experimental; needs useCsr).

checkoutLatest applies Lance writes as a delta over the base CSR, and rebuilds on its own only once pending changes pass 25% of the base. This rebuilds every CSR that carries a delta now, at the version the engine is pinned to. It scans every edge again, so call it after a bulk load or at a quiet time. It doesn't move to newer versions: call checkoutLatest first for that. Query results never change. See Rebuilding the CSR.

Returns

Promise\<void>

optimizeDatasets()
TypeScript
optimizeDatasets(options?): Promise<Record<string, DatasetOptimizeStats>>;

Compact the engine's Lance datasets, move it onto them and delete old versions.

Every write to a Lance dataset makes a new version, and appends leave small fragments that slow scans down. This runs the maintenance Lance and LanceDB recommend, and keeps the engine in step with it. For each Lance dataset the engine reads, it opens the newest version (including writes made through other handles, such as a LanceDB table), compacts small fragments into larger ones, moves the engine to the new versions as checkoutLatest does, then deletes versions older than cleanupOlderThanMs, except the latest and tagged ones. The engine moves before the cleanup, so it never reads a deleted version. Lance indexes aren't updated with new rows. See Compaction and old versions.

Parameters
Parameter Type Description
options? { cleanupOlderThanMs?: number; } -
options.cleanupOlderThanMs? number Delete versions older than this many milliseconds (default 7 days, as in LanceDB's optimize()). Other readers pinned to an older version, including queries already running on this engine, fail once their version is deleted, so use a short window only when nothing else reads the datasets.
Returns

Promise\<Record\<string, DatasetOptimizeStats>>

Per Lance dataset, what compaction and cleanup did. Arrow inputs aren't listed.

Throws

LanceCsrError InvalidArgument if cleanupOlderThanMs is negative; Runtime if a dataset can't be opened, compacted or cleaned up. Datasets compacted before the failure stay compacted.

create()
TypeScript
static create(
   config, 
   datasets, 
   options?
): Promise<CypherEngine>;

Open the datasets and build the engine. Lance datasets are pinned, not read; with useCsr the indexes are built here, on a background thread.

Parameters
Parameter Type Description
config GraphConfig The graph mapping.
datasets Record\<string, Dataset> The tables, keyed by node label or relationship type.
options? CypherEngineOptions CSR and partitioning options.
Returns

Promise\<CypherEngine>

Throws

LanceCsrError with code InvalidArgument if datasets is empty, a configured key or endpoint column is missing, targetPartitions is outside 1 to 1024, persistCsr isn't true, false or "load", or it is set without useCsr; Runtime if a dataset can't be opened.

Throws

TypeError if config isn't a GraphConfig or a dataset has an unsupported type.


CypherQuery

One parsed Cypher query, run against the datasets passed to each call.

Builder methods return a new query. Datasets are read into memory for each call; use CypherEngine to register them once and run many queries.

Example

TypeScript
const result = await new CypherQuery("MATCH (p:Person) WHERE p.age > $min RETURN p.name")
  .withConfig(config)
  .withParameter("min", 30)
  .execute({ Person: people });

Constructors

Constructor
TypeScript
new CypherQuery(queryText): CypherQuery;
Parameters
Parameter Type Description
queryText string The Cypher query.
Returns

CypherQuery

Throws

LanceCsrError with code InvalidArgument if queryText doesn't parse.

Methods

execute()
TypeScript
execute(datasets, options?): Promise<Table<any>>;

Run the query.

Parameters
Parameter Type Description
datasets Record\<string, Dataset> The tables, keyed by node label or relationship type. They are read into memory for this call.
options? ExecuteOptions & object strategy (default ExecutionStrategy.DataFusion) and timeoutMs.
Returns

Promise\<Table\<any>>

The query result.

Throws

LanceCsrError with code InvalidArgument if the query is invalid or a dataset is missing; NotImplemented for an unsupported Cypher feature or ExecutionStrategy.LanceNative; Timeout past timeoutMs; Runtime if execution fails.

executeWithNamespace()
TypeScript
executeWithNamespace(namespace, strategy?): Promise<Table<any>>;

Run the query, reading each label from <baseUri>/<label>.lance.

Parameters
Parameter Type Description
namespace DirNamespace Where the datasets are.
strategy? ExecutionStrategy How to run the query; the default is ExecutionStrategy.DataFusion.
Returns

Promise\<Table\<any>>

executeWithVectorRerank()
TypeScript
executeWithVectorRerank(datasets, vectorSearch): Promise<Table<any>>;

Run the query, then rank its rows by vector similarity.

This is the common GraphRAG pattern: find candidates by graph traversal, then rerank them by similarity. With VectorSearch.useLanceIndex(true) and Lance datasets, the Lance index is searched first instead. See Vector search.

Parameters
Parameter Type Description
datasets Record\<string, Dataset> -
vectorSearch VectorSearch The ranking. Its column is a returned column, such as "d.embedding".
Returns

Promise\<Table\<any>>

At most topK rows, closest first.

explain()
TypeScript
explain(datasets): Promise<string>;

The plans for the query, without running it.

Parameters
Parameter Type
datasets Record\<string, Dataset>
Returns

Promise\<string>

The graph logical plan, the DataFusion logical plan and the physical plan.

nodeLabels()
TypeScript
nodeLabels(): string[];

The node labels the query uses, including UNION branches, unordered.

Returns

string[]

parameters()
TypeScript
parameters(): Record<string, Scalar>;

The bound parameters, as the engine receives them (a Date becomes ISO text).

Returns

Record\<string, Scalar>

queryText()
TypeScript
queryText(): string;

The query text.

Returns

string

relationshipTypes()
TypeScript
relationshipTypes(): string[];

The relationship types the query uses, with UNION branches, unordered.

Returns

string[]

toSql()
TypeScript
toSql(datasets, dialect?): Promise<string>;

Export the query as SQL joins. Only supported expressions are exported. See From Cypher to SQL.

Parameters
Parameter Type Description
datasets Record\<string, Dataset> The tables, keyed by node label or relationship type; their schemas shape the SQL.
dialect? SqlDialect The SQL dialect; the default is SqlDialect.Default.
Returns

Promise\<string>

Throws

LanceCsrError with code NotImplemented if a runtime-only Cypher function has no faithful SQL translation.

toString()
TypeScript
toString(): string;
Returns

string

variables()
TypeScript
variables(): string[];

The variables the query uses, including UNION branches, unordered.

Returns

string[]

withConfig()
TypeScript
withConfig(config): CypherQuery;

Set the graph config. Required before running the query.

Parameters
Parameter Type
config GraphConfig
Returns

CypherQuery

A new query with the config set.

withParameter()
TypeScript
withParameter(key, value): CypherQuery;

Bind $key to value.

Parameters
Parameter Type Description
key string The parameter name, without $.
value Parameter The value, of a type that CypherEngine.execute accepts in params.
Returns

CypherQuery

A new query with the parameter bound.


DirNamespace

Resolves each table name to the Lance dataset <baseUri>/<name>.lance.

Use it with CypherQuery.executeWithNamespace.

Constructors

Constructor
TypeScript
new DirNamespace(baseUri): DirNamespace;
Parameters
Parameter Type Description
baseUri string The directory that holds the datasets.
Returns

DirNamespace

Properties

baseUri
TypeScript
readonly baseUri: string;

The directory that holds the datasets.


GraphConfig

An immutable mapping from tables to a property graph.

Create one with GraphConfig.builder; there is no public constructor. See Graph schema.

Methods

nodeLabels()
TypeScript
nodeLabels(): string[];

The configured node labels, lower-cased, in no particular order.

Returns

string[]

relationshipTypes()
TypeScript
relationshipTypes(): string[];

The configured relationship types, lower-cased, in no particular order.

Returns

string[]

toString()
TypeScript
toString(): string;
Returns

string

builder()
TypeScript
static builder(): GraphConfigBuilder;

Start a new, empty builder: the same as new GraphConfigBuilder().

Returns

GraphConfigBuilder


GraphConfigBuilder

Builds a GraphConfig from node and relationship tables.

new GraphConfigBuilder() is the same as GraphConfig.builder(). Every method returns a new builder and leaves this one unchanged.

Example

TypeScript
const config = GraphConfig.builder()
  .nodeTable("Person", "id")
  .relTable("KNOWS", "Person", "Person", "src_id", "dst_id")
  .build();

Constructors

Constructor
TypeScript
new GraphConfigBuilder(): GraphConfigBuilder;
Returns

GraphConfigBuilder

Methods

build()
TypeScript
build(): GraphConfig;

Validate the tables and return the config.

Returns

GraphConfig

Throws

LanceCsrError with code InvalidArgument if the configuration is invalid, for example when a relationship's endpoint label has no node table.

nodeTable()
TypeScript
nodeTable(label, primaryKey): GraphConfigBuilder;

Add a node table.

The nodes labelled label are the rows of the dataset named label, each identified by its primaryKey column.

Parameters
Parameter Type Description
label string The node label, and the name of its dataset (for example "Person").
primaryKey string The column that identifies each node.
Returns

GraphConfigBuilder

A new builder with the node table added.

relTable()
TypeScript
relTable(
   relType, 
   fromTable, 
   toTable, 
   src, 
   dst
): GraphConfigBuilder;

Add a relationship table.

The edges of type relType are the rows of the dataset named relType, from fromTable nodes to toTable nodes. Both node tables must be added by the time GraphConfigBuilder.build runs.

Parameters
Parameter Type Description
relType string The relationship type, and the name of its dataset (for example "KNOWS").
fromTable string The node table at the source end.
toTable string The node table at the target end.
src string The column holding the source node's primary key.
dst string The column holding the target node's primary key.
Returns

GraphConfigBuilder

A new builder with the relationship table added.


LanceCsrError

An error from the query engine. Arguments of the wrong type raise TypeError instead.

Extends

  • Error

Constructors

Constructor
TypeScript
new LanceCsrError(
   code, 
   message, 
   options?
): LanceCsrError;
Parameters
Parameter Type
code ErrorCode
message string
options? ErrorOptions
Returns

LanceCsrError

Overrides

Error.constructor

Properties

code
TypeScript
readonly code: ErrorCode;

What went wrong; see ErrorCode.


RecordBatchStream

A query result read one batch at a time: an async iterable of Arrow record batches.

Batches are computed as they are read. Scans, filters and projections stream with bounded memory; joins, sorts and aggregations may still buffer. The stream keeps its snapshot alive, so a concurrent checkoutLatest doesn't affect it. Breaking out of a for await loop, or calling RecordBatchStream.close, stops the query.

Example

TypeScript
const stream = await engine.executeBatches("MATCH (p:Person) RETURN p.name");
for await (const batch of stream) {
  console.log(batch.numRows);
}

Implements

  • AsyncIterable\<RecordBatch>

Properties

schema
TypeScript
readonly schema: Schema;

The schema of every batch.

Methods

[asyncIterator]()
TypeScript
[asyncIterator](): AsyncIterator<RecordBatch<any>>;
Returns

AsyncIterator\<RecordBatch\<any>>

Implementation of

AsyncIterable.[asyncIterator]

close()
TypeScript
close(): Promise<void>;

Stop the query and release what it holds. Reading afterwards returns null.

Returns

Promise\<void>

next()
TypeScript
next(): Promise<RecordBatch<any> | null>;

The next batch, or null at the end.

Returns

Promise\<RecordBatch\<any> | null>

Throws

LanceCsrError with code Timeout once the query's deadline has passed, or Runtime if execution fails.


SqlEngine

Run many SQL queries on the same datasets, with graph patterns given a graph.

Each dataset is a table under its lower-cased name. Lance datasets are scanned in place, pinned to the version given, with column and filter pushdown; Arrow inputs are held in memory. With a config, a GRAPH_TABLE clause embeds a Cypher graph pattern, and with useCsr its hops run on the CSR. See Graph patterns in SQL.

Plans are cached per snapshot, as CypherEngine caches Cypher templates.

Example

TypeScript
const engine = await SqlEngine.create({
  person: tableFromArrays({ id: Int32Array.from([1, 2]), name: ["Alice", "Bob"] }),
  knows: tableFromArrays({ src: Int32Array.from([1]), dst: Int32Array.from([2]) }),
});
const result = await engine.execute(
  "SELECT p.name FROM person p JOIN knows k ON p.id = k.src WHERE k.dst = $dst",
  { dst: 2 },
);

Methods

checkoutLatest()
TypeScript
checkoutLatest(): Promise<void>;

Move every Lance dataset to its latest version, as CypherEngine.checkoutLatest does.

Returns

Promise\<void>

execute()
TypeScript
execute(
   sql, 
   params?, 
   options?
): Promise<Table<any>>;

Run a SQL query and return the whole result.

Parameters
Parameter Type Description
sql string The SQL query.
params? Record\<string, Parameter> | null Values for $name parameters, as for CypherEngine.execute.
options? ExecuteOptions timeoutMs: milliseconds for the whole query.
Returns

Promise\<Table\<any>>

Throws

LanceCsrError with code InvalidArgument if the query is invalid, Timeout past timeoutMs, or Runtime if execution fails.

explain()
TypeScript
explain(
   sql, 
   params?, 
   options?
): Promise<string>;

The plans for a SQL query, without running it unless analyze is set.

Parameters
Parameter Type
sql string
params? Record\<string, Parameter> | null
options? ExplainOptions
Returns

Promise\<string>

The logical and physical plans; with analyze, the physical plan with each operator's metrics.

create()
TypeScript
static create(datasets, options?): Promise<SqlEngine>;

Open the datasets and build the engine.

Parameters
Parameter Type Description
datasets Record\<string, Dataset> The tables, keyed by the names queries use; with a config, also by node label or relationship type, as for CypherEngine.
options? SqlEngineOptions -
Returns

Promise\<SqlEngine>

Throws

LanceCsrError with code InvalidArgument if datasets is empty, useCsr is set without a config, or a configured column is missing.

fromEngine()
TypeScript
static fromEngine(engine): SqlEngine;

SQL over a CypherEngine's snapshot, sharing its datasets, CSR and statistics.

checkoutLatest on either engine moves only that engine: the other keeps the snapshot it holds.

Parameters
Parameter Type
engine CypherEngine
Returns

SqlEngine


SqlQuery

One SQL query, run against the datasets passed to each call.

Each dataset is a table under its lower-cased name, read into memory for the call. Use SqlEngine to register datasets once and run many queries.

Constructors

Constructor
TypeScript
new SqlQuery(sql): SqlQuery;
Parameters
Parameter Type Description
sql string The SQL query.
Returns

SqlQuery

Methods

execute()
TypeScript
execute(datasets): Promise<Table<any>>;

Run the query.

Parameters
Parameter Type Description
datasets Record\<string, Dataset> The tables, keyed by the names the query uses.
Returns

Promise\<Table\<any>>

Throws

LanceCsrError with code InvalidArgument if the query is invalid, or Runtime if execution fails.

explain()
TypeScript
explain(datasets): Promise<string>;

The logical and physical plans for the query, without running it.

Parameters
Parameter Type
datasets Record\<string, Dataset>
Returns

Promise\<string>

sql()
TypeScript
sql(): string;

The query text.

Returns

string

toString()
TypeScript
toString(): string;
Returns

string


VectorSearch

An immutable builder for vector similarity search.

Every method except VectorSearch.search returns a new builder. Pass the builder to search to rank an Arrow table, or to executeWithVectorRerank on CypherEngine or CypherQuery to rerank a Cypher result. This is separate from the vector_distance() and vector_similarity() Cypher functions. See Vector search.

Example

TypeScript
const search = new VectorSearch("d.embedding")
  .queryVector([0.1, 0.2, 0.3])
  .metric(DistanceMetric.Cosine)
  .topK(5);

Constructors

Constructor
TypeScript
new VectorSearch(column): VectorSearch;
Parameters
Parameter Type Description
column string The vector column to rank by, such as "embedding" or "d.embedding".
Returns

VectorSearch

Methods

distanceColumnName()
TypeScript
distanceColumnName(name): VectorSearch;

Name the distance column; the default is "_distance".

Parameters
Parameter Type
name string
Returns

VectorSearch

includeDistance()
TypeScript
includeDistance(include): VectorSearch;

Add the distance as a column (the default), or leave it out.

Parameters
Parameter Type
include boolean
Returns

VectorSearch

metric()
TypeScript
metric(metric): VectorSearch;

Set the distance metric; the default is DistanceMetric.L2.

Parameters
Parameter Type
metric DistanceMetric
Returns

VectorSearch

queryVector()
TypeScript
queryVector(vector): VectorSearch;

Set the vector to compare with. Required before searching.

Parameters
Parameter Type
vector ArrayLike\<number>
Returns

VectorSearch

TypeScript
search(table): Promise<Table<any>>;

Brute-force search table.

Parameters
Parameter Type Description
table Table\<any> | RecordBatch\<any> The rows to search, with the vector column.
Returns

Promise\<Table\<any>>

At most topK rows, sorted by distance, closest first.

Throws

LanceCsrError with code InvalidArgument if no query vector is set or the column doesn't exist, or Runtime if the search fails.

topK()
TypeScript
topK(k): VectorSearch;

Keep at most k rows; the default is 10.

Parameters
Parameter Type
k number
Returns

VectorSearch

useLanceIndex()
TypeScript
useLanceIndex(enabled): VectorSearch;

Set whether reranking queries a Lance ANN index first; false by default.

When the datasets are Lance datasets, CypherQuery.executeWithVectorRerank searches the Lance approximate-nearest-neighbour index first and then runs the Cypher query on the top-k rows. This can be much faster on large datasets, but it can change the results when the query also filters, because the filter then applies to the top-k rows only.

Parameters
Parameter Type
enabled boolean
Returns

VectorSearch

Interfaces

CsrStats

Statistics for one CSR adjacency index, from CypherEngine.csrStats().

Properties

Property Type Description
baseVersion? number The relationship dataset version of the last full build; absent for Arrow input.
buildMs number Wall time of that build or delta, both directions, in milliseconds.
deltaEdges number Edges appended since the last full build, held outside the base CSR.
edges number Live indexed edges (null endpoints are skipped).
storeError? string Why the base CSR couldn't be stored with persistCsr: true; absent when it was, or when nothing is stored. It stays set while the engine keeps that base, through deltas.
tombstones number Edges removed since the last full build, held outside the base CSR.
unindexedEdges number Live edges outside the base CSR: appended since its last full build and not since removed.
update "build" | "rebuild" | "loaded" | "delta" | "reused" How the last build, checkoutLatest() or optimizeCsr() produced it.
version? number The relationship dataset version it reflects; absent for Arrow input.

CypherEngineOptions

Options for CypherEngine.create.

Properties

Property Type Description
persistCsr? boolean | "load" Experimental, needs useCsr unless false. With true, store each relationship dataset's CSR inside the dataset's own directory, at _lance_csr/<version>.arrow, and load it instead of building when an engine starts. Changes since the stored version apply as a delta under the same 25% threshold as checkoutLatest; past it, the CSR is rebuilt and stored again. Arrow inputs aren't stored. A dataset that can't be written is built in memory, and the engine emits a process warning and reports the error as storeError in csrStats(). With "load", load stored files the same way but never write to the datasets: a CSR that can't be loaded is built in memory, as with false.
targetPartitions? number A target from 1 to 1024 for DataFusion query partitioning; left out, DataFusion's default. checkoutLatest preserves it. It is not a thread or memory limit.
useCsr? boolean Build the experimental CSR index for relationship types with integer endpoints, and node indexes for labels with unique integer keys.

DatasetOptimizeStats

What CypherEngine.optimizeDatasets() did to one Lance dataset.

Properties

Property Type Description
bytesRemoved number Bytes of files cleanup deleted.
fragmentsAdded number Fragments compaction wrote in their place.
fragmentsRemoved number Small fragments compaction rewrote.
oldVersions number Old versions cleanup deleted.

ExecuteOptions

Options for running a query.

Properties

Property Type Description
timeoutMs? number Milliseconds for the whole query; left out, no deadline.

ExplainOptions

Options for explaining a query.

Properties

Property Type Description
analyze? boolean Run the query, like SQL's EXPLAIN ANALYZE, and show each physical operator's metrics (output rows, elapsed compute time and more) in place of the plain physical plan. The query runs to completion; its rows are discarded.

GraphExport

A graph as compressed sparse rows over dense node ids, from CypherEngine.exportGraph().

Nodes are numbered 0 to numNodes - 1, and the neighbours of node i are outIndices[outIndptr[i]] up to outIndices[outIndptr[i + 1]]. nodeKeys maps each dense id back to its node's key. The vectors wrap typed arrays built in Rust. See Drawing the whole graph.

Properties

Property Type Description
directed boolean Whether the arrays describe a directed graph.
droppedEdges number Edges left out because an endpoint key isn't in its node table. Edges with a null endpoint are skipped and not counted.
inIndices Vector\<Uint64> | null Each node's in-neighbours, sorted, without duplicates; null for an undirected graph.
inIndptr Vector\<Uint64> | null Offsets into inIndices; null for an undirected graph.
labelRanges Record\<string, [number, number]> Each node label's dense ids, as [start, end] with end excluded. Labels get consecutive ranges in name order, so equal keys in two labels stay distinct.
nodeKeys Vector\<Int64> The key of each dense id. Each label's nodes are in the order its table is scanned; rows with a null key are left out.
numNodes number Number of nodes. Dense ids run from 0 to numNodes - 1.
outIndices Vector\<Uint64> Each node's out-neighbours, sorted, without duplicates. An undirected graph lists every edge in both directions and a self-loop once.
outIndptr Vector\<Uint64> Offsets into outIndices, numNodes + 1 entries.

LanceDataset

A Lance dataset on local disk or object storage, opened by URI.

CypherEngine and SqlEngine read it lazily, pinned to version (the latest when left out). CypherQuery and SqlQuery read it into memory for each call.

Properties

Property Type Description
storageOptions? Record\<string, string> Lance storage options, such as object-store credentials and region.
uri string Where the dataset is, such as "data/person.lance" or "s3://bucket/person.lance".
version? number The version to read; the latest when left out.

NodeIndexStats

Statistics for one node index, from CypherEngine.nodeIndexStats().

Properties

Property Type Description
buildMs number Wall time of the build, in milliseconds.
rows number Indexed node rows.
version? number The node dataset version it reflects; absent for Arrow input.

SqlEngineOptions

Options for SqlEngine.create.

Properties

Property Type Description
config? GraphConfig The graph GRAPH_TABLE patterns match. Without one, GRAPH_TABLE fails with InvalidArgument.
useCsr? boolean Build the experimental CSR index, as for CypherEngine. Needs a config.

Type Aliases

Dataset

TypeScript
type Dataset = Table | RecordBatch | LanceDataset;

A table to query: an Arrow Table or RecordBatch held in memory, or a Lance dataset.


DistanceMetric

TypeScript
type DistanceMetric = native.DistanceMetric;

The distance VectorSearch ranks rows by; smaller is closer. L2 is Euclidean distance, Cosine is 1 − cosine similarity and Dot is the negative dot product.


ErrorCode

TypeScript
type ErrorCode = "InvalidArgument" | "NotImplemented" | "Timeout" | "Runtime";

The kinds of LanceCsrError, matching the Python package's exceptions:

  • InvalidArgument (Python ValueError): an invalid query, config, parameter or option.
  • NotImplemented (Python NotImplementedError): a Cypher feature that parses but isn't supported.
  • Timeout (Python TimeoutError): the query ran past its timeoutMs.
  • Runtime (Python RuntimeError): a dataset couldn't be read, or execution failed.

ExecutionStrategy

TypeScript
type ExecutionStrategy = native.ExecutionStrategy;

How CypherQuery.execute runs a query. DataFusion (the default and only implemented one) plans and runs it with DataFusion; LanceNative is reserved and fails with NotImplemented.


Parameter

TypeScript
type Parameter = 
  | number
  | bigint
  | string
  | boolean
  | Date
  | null
  | Parameter[]
  | {
[key: string]: Parameter;
};

A value for a $name query parameter.

Whole numbers are sent as integers and other numbers as floats. A bigint must fit in a signed 64-bit integer. A Date is sent as ISO 8601 text, which compares with timestamp and date columns.


Scalar

TypeScript
type Scalar = 
  | number
  | string
  | boolean
  | null
  | Scalar[]
  | {
[key: string]: Scalar;
};

A bound parameter value, as CypherQuery.parameters() returns it.


SqlDialect

TypeScript
type SqlDialect = native.SqlDialect;

The SQL dialect CypherQuery.toSql writes: Default (generic DataFusion SQL), Spark, PostgreSql, MySql or Sqlite.

Variables

DistanceMetric

TypeScript
const DistanceMetric: typeof DistanceMetric = native.DistanceMetric;

The distance VectorSearch ranks rows by; smaller is closer. L2 is Euclidean distance, Cosine is 1 − cosine similarity and Dot is the negative dot product.


ExecutionStrategy

TypeScript
const ExecutionStrategy: typeof ExecutionStrategy = native.ExecutionStrategy;

How CypherQuery.execute runs a query. DataFusion (the default and only implemented one) plans and runs it with DataFusion; LanceNative is reserved and fails with NotImplemented.


SqlDialect

TypeScript
const SqlDialect: typeof SqlDialect = native.SqlDialect;

The SQL dialect CypherQuery.toSql writes: Default (generic DataFusion SQL), Spark, PostgreSql, MySql or Sqlite.


version

TypeScript
const version: string = VERSION;

The package version.