Skip to content

Provider: ArangoDB

matthew edited this page May 12, 2026 · 1 revision

Provider: ArangoDB

The non-Cypher portability proof. ArangoDB is a multi-model store whose query language is AQL (a JavaScript-shaped declarative language), with a step-based graph traversal syntax (FOR v, e IN min..max OUTBOUND start edge_collection) that bears no syntactic resemblance to Cypher. Where Neo4j and AGE both speak Cypher dialects, the ArangoDB provider exercises the framework's seam against a fundamentally different query language and a non-Bolt, non-Postgres wire (HTTP + JSON).

The architectural payoff: it works without changing the abstraction — the same TraversalAst, IStatementEmitter, IResultMaterializer, and IGraphTransactionOpener contracts that satisfy Cypher also satisfy AQL. The framework's earlier concern that the linear-segment-list AST was "Cypher-shaped" turned out to be syntactic, not structural.

Composition root

Eager form:

using Microsoft.Extensions.DependencyInjection;
using OnixLabs.ElementFramework;

services.AddGraphContext<BlogGraphContext>(builder =>
    builder.UseArango(
        endpoint:     new Uri("http://localhost:8529"),
        databaseName: "_system",
        username:     "root",
        password:     "password"));

Lazy form (e.g., Testcontainers):

services.AddGraphContext<BlogGraphContext>(builder =>
    builder.UseArango(
        endpointFactory: () => fixture.Endpoint,
        databaseName:    "_system",
        username:        "root",
        password:        "test"));

With logger factory:

services.AddGraphContext<BlogGraphContext>((sp, builder) =>
    builder
        .UseLoggerFactory(sp.GetRequiredService<ILoggerFactory>())
        .UseArango(new Uri("http://localhost:8529"), "_system", "root", "password"));

One-time schema bootstrap

Unlike Cypher-family stores, ArangoDB does not auto-create collections on first write. The provider ships an opt-in helper that walks the registered model and creates any missing document / edge collections:

using IServiceScope scope = provider.CreateScope();
BlogGraphContext context = scope.ServiceProvider.GetRequiredService<BlogGraphContext>();

await ArangoSchemaBootstrap.EnsureCollectionsAsync(
    context,
    new Uri("http://localhost:8529"),
    "_system",
    "root",
    "password");

// Now safe to use the context
context.Nodes<Author>().Add(author);
await context.SaveChangesAsync();

Call once at application startup (or once per test class in integration tests). Idempotent — already-existing collections are left alone. This is the reason IGraphModel.Nodes / Relationships are public enumerations and GraphContext.Model is a public ([EditorBrowsable(Advanced)]) getter.

Client caching: ArangoClientCache

A process-wide ConcurrentDictionary<(endpoint, database, username, password), ArangoDBClient>. Each cached client wraps an HttpApiTransport and a custom ArangoSerialization. No eviction — same trade-off as the other providers; issue #5.

Serialization: ArangoSerialization

ArangoDBNetStandard 3.1.0 ships with Newtonsoft.Json as its default serializer, not System.Text.Json. The framework installs a custom IApiClientSerialization to override two defaults that would otherwise corrupt round-tripped data:

  • DateParseHandling.None on the deserializer. Newtonsoft's default (DateParseHandling.DateTime) auto-detects ISO-8601-shaped strings during JSON parsing and parses them into DateTime values with the offset converted to local time. By the time the materializer sees the value, the offset is gone. Forcing DateParseHandling.None keeps date strings as strings so ArangoResultMaterializer.Convert can run DateTimeOffset.Parse under DateTimeStyles.RoundtripKind and preserve the offset.
  • ProcessDictionaryKeys = false on the camel-case naming strategy used for serialization. The default CamelCasePropertyNamesContractResolver camel-cases not just C# property names but also Dictionary<string, object?> keys. Our bind-vars payload carries dictionary keys like "WrittenAt" and "_key" that must reach ArangoDB verbatim; without this flag, WrittenAt would be serialized as writtenAt on write and missed on read. C# property names on ArangoDBNetStandard's own request bodies (BatchSize → batchSize) still get camel-cased.

AQL emission

The framework's identity model maps cleanly onto ArangoDB's document conventions:

  • Each node label → a document collection of that name. The node's key value is mirrored into _key (ArangoDB's per-collection unique identifier) as well as stored under the property's own name.
  • Each relationship type → an edge collection of that name. Edges store _from = "{startCollection}/{startKey}" and _to = "{endCollection}/{endKey}" plus their own properties. Edges have no separate key in the framework's model; disconnect removes every edge matching the endpoint pair.

Bind variables follow ArangoDB's convention: value bind variables use the name verbatim in the dictionary (referenced in AQL as @name), collection bind variables use a single leading @ in the key (referenced in AQL as @@name). The emitter never inlines collection names — they always flow through @@col / @@edge bind vars.

Sample AQL:

// EmitAdd<Author>
INSERT @doc INTO @@col

// EmitFindById<Author>
FOR n IN @@col FILTER n._key == @key LIMIT 1 RETURN { n: n }

// EmitConnect<Author, Wrote, Post>
INSERT @doc INTO @@edge   // doc = { _from: "Author/...", _to: "Post/...", WrittenAt: ... }

// EmitTraversal for a 2-segment outgoing pattern
FOR a IN @@c0
  FOR p, w IN 1..1 OUTBOUND a @@c1
    FILTER a.Name == @p0
    RETURN { p: p }

ArangoTraversalEmitter handles the traversal-AST → AQL translation. Direction maps trivially: Outgoing → OUTBOUND, Incoming → INBOUND, Either → ANY. Predicates lower to AQL FILTER, ordering to SORT, skip/take to LIMIT.

AQL gotcha: there's no built-in ENDS_WITH function in AQL 3.12. The emitter falls back to SUBSTRING(text, LENGTH(text) - LENGTH(@p)) == @p — safer than LIKE("%..." ) because it doesn't collide with literal % / _ characters in the suffix.

Execution: ArangoRawStatementExecutor

The executor delegates to ArangoDBClient.Cursor. Each statement is sent as an AQL string plus a bind-vars dictionary; subsequent batches are fetched via the cursor's pagination API as the consumer pulls rows. Async path is a real async iterator; sync path drains eagerly.

Ambient transaction routing reads IGraphTransactionOpener.Active: when it returns an ArangoGraphTransaction, the executor sets CursorHeaderProperties.TransactionId to the stream-transaction ID. The initial PostCursorAsync carries the header; continuation fetches via PutCursorAsync do not — the cursor is server-side bound to the transaction that opened it, so the header is redundant (and ArangoDBNetStandard 3.1.0's PutCursorAsync doesn't accept one).

Transactions: Stream Transactions

ArangoDB Stream Transactions require every collection touched by the transaction to be declared up-front. The framework's ChangeTracker opens the transaction before draining the pending queue, so the provider doesn't yet know which collections will be involved. The pragmatic workaround: at begin time, the opener lists every non-system collection in the bound database (Collection.GetCollectionsAsync(ExcludeSystem = true)) and declares them all as read+write, plus AllowImplicit = true. One extra HTTP call per transaction begin; avoids coupling the opener to IGraphModel.

Commit / abort go through Transaction.CommitTransaction / Transaction.AbortTransaction. Same one-ambient-at-a-time invariant and same dispose-path best-effort-abort logging as the other providers.

Materialization: ArangoResultMaterializer, ArangoJsonReader

Rows reach the materializer as IReadOnlyDictionary<string, object?> produced by ArangoJsonReader, which walks the JObject rows returned by ArangoDBNetStandard's cursor and converts them recursively to a tree of Dictionary<string, object?>, List<object?>, and primitive boxed CLR values. Integer JSON numbers become long; fractional or out-of-range numbers become double; date-shaped strings stay strings (thanks to DateParseHandling.None).

The materializer's alias-keyed reads follow the same convention as the other providers: "n" for the node alias, "r" for the edge alias, "cnt" for the existence count. CLR conversion mirrors ArangoPropertySerializer: ISO-8601 string → DateTimeOffset / DateTime, hyphenated string → Guid, member-name string → enum, primitive widening via Convert.ChangeType under invariant culture.

Conformance

All conformance tests pass against arangodb/arangodb:3.12 via Testcontainers, except the four raw-statement Cypher tests (skipped because Arango's raw surface is AQL, not Cypher — same pattern as AGE).

Diagnostics caveat

Unlike Neo4j (whose driver has its own ActivitySource) and AGE (whose Npgsql 9.x driver has one), ArangoDBNetStandard 3.1.0 does not emit a wire-layer ActivitySource. The framework's Arango.ExecuteStatement / Arango.TranslateTraversal spans are the only observability of the round-trip; wire-level HTTP timing would need to come from HttpClient instrumentation separately (AddHttpClientInstrumentation() in OpenTelemetry).

Full example

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using OnixLabs.ElementFramework;

ServiceCollection services = new();
services.AddLogging(builder => builder.AddConsole());
services.AddGraphContext<BlogGraphContext>((sp, builder) =>
    builder
        .UseLoggerFactory(sp.GetRequiredService<ILoggerFactory>())
        .UseArango(new Uri("http://localhost:8529"), "_system", "root", "password"));

await using ServiceProvider provider = services.BuildServiceProvider();
using IServiceScope scope = provider.CreateScope();
BlogGraphContext context = scope.ServiceProvider.GetRequiredService<BlogGraphContext>();

// One-time schema setup — call once at startup
await ArangoSchemaBootstrap.EnsureCollectionsAsync(
    context, new Uri("http://localhost:8529"), "_system", "root", "password");

Author ada = new() { Id = Guid.NewGuid(), Name = "Ada", JoinedAt = DateTimeOffset.UtcNow };
context.Nodes<Author>().Add(ada);
await context.SaveChangesAsync();

Author? loaded = context.Nodes<Author>().FindById(ada.Id);
Console.WriteLine($"Loaded: {loaded?.Name}");