strata · graphs

Graph indexes and graph queries in Strata

Strata keeps a table's text, structured fields and vectors in one file and queries them with SQL. Rows can now link to other rows. A traversal, a shortest path or personalized PageRank runs in the same statement as BM25, filters and vector search, and can start from any of them. This page covers how edges are stored and resolved, the SQL, the planner's part, speed against SQLite and an in-memory graph, and whether the graph helps search when a vector search is the way into it. It does: on arXiv, the papers cited by a new paper's two nearest neighbours find twice as many of its references as vector search alone. A graph built from the vectors themselves does not help.

Finding a paper's references
nDCG@20 0.123 → 0.253

Vector search, then the papers cited by the two nearest papers ranked by similarity, on 484 held-out arXiv papers. Hybrid BM25 and vector search reaches 0.160. p < 0.0001.

Edges built from vectors
no gain

A row's ten most similar rows as its edges: a traversal over them returns what vector search already found, or worse.

Two hops both ways, p95
14.8 → 1.6 ms

SQLite recursive CTE against Strata on 168k papers and 1.15M citations, 3,790 rows on average, on an Apple M2. An in-memory CSR takes 0.49 ms.

PageRank, 1M rows
21.4 → 5.8 ms

Personalized PageRank (ε = 10⁻⁴) on a power-law graph of 10M edges, before and after three changes to the index and the push loop, on the cloud VM where they were made. On the M2 it takes 3.5 ms, and the CSR 0.66 ms.

Rows are nodes

Graph databases keep nodes and edges in stores of their own. Strata keeps its one table. A row is a node, and an EDGES field holds the row's outgoing edges: a JSON array of targets, each a primary key of the same table, optionally with a label and a positive weight.

-- id KEYWORD PRIMARY KEY, title TEXT, body TEXT, year INT, emb VECTOR(512), cites EDGES
INSERT ... ('p1', 'Attention is all you need', ..., 2017, [...],
            '["p7", ["extends", "p9"], ["refutes", "p11", 0.5]]')

Formally, a snapshot \(S\) holds rows \(V\) with keys \(\kappa: V \to K\), and edges

\[ E \subseteq V \times K \times L \times \mathbb{R}_{>0}, \qquad (u, k, \ell, w): \text{row } u \text{ points at key } k \text{ with label } \ell \text{ and weight } w. \]

An edge is resolved at query time:

\[ \rho_S(k) = \text{the live row } v \in V \text{ with } \kappa(v) = k, \text{ if any}. \]

A key has at most one live row in a snapshot, so \(\rho_S\) is a function. When it has none (the target was deleted, or never existed), the edge dangles and traversals skip it, as a foreign key without a constraint would.

Edges belong to their source row and point at keys, not at storage positions. They are written, logged, updated, deleted, merged and snapshotted with the row, and nothing else in the engine had to change.

Targets as keys are what make this work. A merge rewrites every docID, and an update moves a row to a newer segment, but neither changes a key, so no edge is ever rewritten. The price is a lookup per hop, which most of the work below goes into making cheap.

Storing edges

Every segment, on disk or built from the memtable, gets one section per indexed EDGES field, read in place through mmap:

One segment's graph section. Out-edges are a CSR over local docIDs. The reverse index groups edges by target key. A hop along an edge uses the same-segment hint when its row is still live, and otherwise the primary-key indexes of the snapshot's segments.

A hop from \(u\) along its edges therefore costs, per edge,

\[ c_{\text{out}} = p_{\text{hint}}\,c_{\text{live}} + (1 - p_{\text{hint}})\bigl(p_{\text{memo}}\,c_{\text{memo}} + (1 - p_{\text{memo}}) \textstyle\sum_{i \le j^*} c_{\text{probe},i}\bigr), \]

where \(p_{\text{hint}}\) is the share of targets built into the same segment and still live, \(p_{\text{memo}}\) the share already resolved in this query, and \(j^*\) the segment where the key is found. A hop against the edges costs one reverse-index probe per segment for \(u\)'s key, then a liveness check per source. The section costs about

\[ b \approx \underbrace{8}_{\text{target}} + \underbrace{4}_{\text{source}} + \underbrace{4 + 4}_{\text{reverse}} + \underbrace{4}_{\text{hint}} + \tfrac{8\,|V| + 16\,|K_E|}{|E|} \text{ bytes per edge}, \]

with \(|K_E|\) the distinct targets. That comes to 27 bytes per edge on arXiv:

The graph section of the full table equals that of a table holding only keys and edges, which loads in under a second.

The SQL

Two predicates, a column and a score join the existing functions. Each takes seeds: a key, a parameter, a tuple of keys, or any subquery over the same table. A subquery can rank, filter and limit like any other query, so a vector search, a BM25 query or a facet filter can be the way into the graph.

-- papers within two citations of p1, either way, nearest first
SELECT id, title, hops() FROM papers
WHERE REACHABLE(cites, 'p1', hops => 2, dir => 'both') ORDER BY hops(), id LIMIT 20;

-- one shortest path, only through surveys
SELECT id, hops() FROM papers
WHERE PATH(cites, 'p1', 'p9', max_hops => 6, through => kind = 'survey') ORDER BY hops();

-- the way in is a vector search: the papers its two best hits cite, by similarity
SELECT id FROM papers
WHERE REACHABLE(cites, (SELECT id FROM papers ORDER BY similarity(emb, :q) DESC LIMIT 2))
ORDER BY similarity(emb, :q) DESC LIMIT 20;

-- personalized PageRank from hybrid hits, fused with both rankings
SELECT id FROM papers ORDER BY rrf(bm25(body, :t), similarity(emb, :q),
    ppr(cites, (SELECT id FROM papers ORDER BY rrf(bm25(body, :t), similarity(emb, :q)) DESC LIMIT 2), weighted => 1)) DESC LIMIT 20;
functionwhat it doesoptions (defaults)
REACHABLE(f, seeds, ...)rows \(v\) with \(m \le d(\text{seeds}, v) \le h\)hops 1, min_hops 1, dir 'out' | 'in' | 'both', label 'a,b', through <predicate>, max_nodes 100000
PATH(f, from, to, ...)the rows of one shortest pathmax_hops 6, dir, label, through
hops()a row's distance, or its position on the path; ORDER BY hops() is nearest first
ppr(f, seeds, ...)personalized PageRank, a score for ORDER BY, rrf and weighted sumsalpha 0.15, eps 1e-4, dir 'both', label, weighted 0 (1: the seeds' subquery scores are the restart weights)
a VECTOR field as fa row's neighbours are its \(k\) most similar rowsk 10, min_sim

through constrains the rows a traversal passes through, and the rest of WHERE constrains the rows it ends at. REACHABLE(f, seeds, hops => 0, min_hops => 0) is the seed set itself, so NOT of it removes the seeds from a result.

Planning and traversal

A traversal does not respect segment boundaries, so graph computations run first, over the whole snapshot. Seeds are resolved, a seed subquery running as a query of its own on the same snapshot, and the traversal runs. Its result becomes, per segment, a materialised document set with exact cardinality, plus each row's distance and PageRank score.

Graph first, then the usual plan. The planner sees a graph predicate as a filter whose size it knows exactly. A vector search over a neighbourhood of a few hundred rows becomes an exact scan of those rows.

The traversals:

\[ \pi = \alpha\, e_S + (1 - \alpha)\, \pi W, \qquad W_{uv} = \frac{w_{uv}}{\sum_{x} w_{ux}}, \]

where \(e_S\) is the restart distribution over the seeds. Every row has an estimate \(p\) and a residual \(r\), with \(r = e_S\) at the start, and pushing a row \(u\) does

\[ p(u) \mathrel{+}= \alpha\, r(u), \qquad r(v) \mathrel{+}= (1 - \alpha)\, r(u)\, W_{uv} \;\; \forall v, \qquad r(u) \leftarrow 0, \]

while some \(r(u) \ge \varepsilon \deg(u)\). Each estimate is then within \(\varepsilon \deg(u)\) of \(\pi(u)\), and the work is bounded by \(1/(\alpha\varepsilon)\) pushes whatever the graph's size. A row is queued only once its residual reaches \(\varepsilon\), the least any threshold can be. Rows that merely received a little mass are never resolved, and resolving them was most of the original cost.

Speed

Two graphs, each queried from 200 random seeds on a warm cache, one thread, through SQL (parsing and planning included; COUNT(*), so that no rows are fetched):

  • arXiv: 168,343 papers (ogbn-arxiv, less 1,000 held out) with 1,148,979 citations, in two segments.
  • Synthetic: a power-law graph of 1,000,000 rows and 9,998,469 edges, in four segments. Row \(i\) links to 10 earlier rows, each the target of a random earlier edge with probability ½ and a uniform earlier row otherwise.

The baselines answer the same queries, and the bench checks that every count and path length agrees:

  • SQLite: an edge table (src, dst) as a WITHOUT ROWID primary key, an index on (dst, src), and recursive CTEs.
  • CSR: the same traversal code on two in-memory arrays. This is the lower bound: no keys, no segments, no SQL.

Against SQLite, the one-hop queries cost about the same: roughly 10–15 µs, mostly parsing and planning on both sides. From two hops on, the gap opens. The tail is where it shows most: two hops both ways on arXiv touch 3,790 rows on average and up to tens of thousands, and their p95 is 1.6 ms in Strata against 14.8 ms in SQLite. The recursive CTE re-expands rows reached at several depths and joins through a B-tree per row, where Strata reads a CSR slice. Shortest paths and PageRank have no practical CTE form.

Against the CSR, Strata pays two costs. About 10 µs of SQL per query dominates small traversals. Resolution dominates large ones: PageRank takes 2.4 times the CSR's time on arXiv and 5.3 times on the million-row graph. A target outside its own segment is a hash probe into each segment's primary-key index until found, a cache miss each. Three changes found by profiling on the cloud VM that first ran these benchmarks cut PageRank on the million-row graph from 21.4 to 5.8 ms there (3.5 ms on the M2):

  • reverse groups by key, with the sources stored inline;
  • same-segment hints and a per-query memo;
  • queueing only rows that can pass the push threshold.

Does the graph help search?

Rows here are nodes with text, vectors and edges at once. The question the engine cannot answer alone is whether the edges add anything to a search that already has the text and the vectors, and whether edges made from the vectors themselves (each row linked to its nearest rows) add anything.

The task: for a new paper, find the papers it cites from its title and abstract. This is citation recommendation, and the same shape as finding the records a new question depends on.

  • 1,000 papers of OGB's test split (809 published in 2019, 191 in 2020, each citing at least five papers) are held out of the table.
  • Each held-out paper's title and abstract is the query. Its references in the table (15.3 on average) are the relevant rows.
  • Vectors come from a static embedder (Model2Vec potion-retrieval-32M, 512 dimensions), the same one Engram uses.

Each method returns 20 papers. Methods that start from vector seeds have one parameter, the number of seeds \(S\), swept from 1 to 50. Papers with even ids choose \(S\) by nDCG@20 (516 queries) and odd ids report it (484 queries), so no reported number was tuned on its own queries. Comparisons are paired over the same queries, with a 95% bootstrap interval and a two-sided sign-flip test:

\[ \mathrm{recall@}k = \frac{|R_k \cap T|}{|T|}, \qquad \mathrm{nDCG@}k = \frac{\sum_{i \le k} \mathbb{1}[r_i \in T] / \log_2(i + 1)}{\sum_{i \le \min(k, |T|)} 1 / \log_2(i + 1)}. \]

Times are from the quality runs on the M2, after one untimed pass per method.

The graph doubles what vector search finds. The best method is also the simplest: take the two papers nearest the query, follow their citations, and rank what they cite by similarity to the query. It reaches nDCG@20 0.253 against 0.123 for vector search, 0.161 for BM25 and 0.160 for hybrid search, in 0.2 ms. Papers on the same topic cite the same work, and the nearest papers' reference lists are a better candidate set than the nearest papers themselves.

PageRank from the same seeds reaches 0.211 at its best (from one seed), below the plain one-hop expansion: on this graph the papers two or three hops away dilute the direct citations. Fusing PageRank with the vector ranking lowers it to 0.179, because the vector ranking's own top results are mostly not references. Fusing BM25, vectors and PageRank from hybrid seeds also reaches 0.211, at the cost of BM25 over long queries (48 ms).

nDCG@20 by number of vector seeds

Report half; horizontal lines are the methods without seeds.

Fewer seeds are better. With more seeds, the citations of papers that are less similar to the query crowd out those of the nearest ones. In a first version of the experiment the seeds themselves stayed in the candidate set. Ranked by similarity, they then took the top places, and from 20 seeds on the "graph" method returned exactly the vector search's results. Every graph method above removes the seeds with NOT REACHABLE(cites, seeds, hops => 0, min_hops => 0).

Vector graph nodes. A VECTOR field can be traversed as a graph, each row's 10 most similar rows being its neighbours. On this task that graph adds nothing:

  • with the seeds kept, it returns what vector search already found (recall@20 0.112 against 0.111 at 10 seeds, on all queries);
  • with them removed, it is worse (nDCG@20 0.079).

A similarity graph only re-expresses the vector space, while citations carry information the text does not. Rows carrying vectors are useful as the way into a graph of real relations, not as a replacement for one. The implicit similarity graph stays in Strata for exploratory queries, cheap at 0.12 ms per hop of 10 neighbours, but it is not what makes the graph worth having.

Limits and next steps

Reproduce

cd strata && cargo test --release                         # graph unit tests and tests/graph.rs among them
# ogbn-arxiv (Open Graph Benchmark) and the papers' titles and abstracts
curl -O https://snap.stanford.edu/ogb/data/nodeproppred/arxiv.zip          # into /home/user/data/graph/arxiv, unzipped into raw/
curl -O https://snap.stanford.edu/ogb/data/misc/ogbn_arxiv/titleabs.tsv.gz
python3 -I scripts/prepare_arxiv.py /home/user/data/graph/arxiv
engram-bench embed --input /home/user/data/graph/arxiv/arxiv.jsonl --out /home/user/data/graph/arxiv/arxiv.f32
cargo build --release --features baselines --bin strata-graph-bench
target/release/strata-graph-bench load                      # holds out 1,000 papers of OGB's test split
target/release/strata-graph-bench latency --sqlite /home/user/data/graph/arxiv/edges.sqlite
target/release/strata-graph-bench quality --seeds 1,2,3,5,10,20,50
python3 scripts/graph_quality_stats.py results/graph/quality_arxiv.rows.jsonl.gz --out results/graph/quality_stats.json
target/release/strata-graph-bench synthetic --nodes 1000000 --sqlite /home/user/data/graph/synthetic.sqlite
python3 scripts/build_graph_report.py                       # this page