Gremlin is imperative and composable. A traversal is a chain of steps - V(), has(), out(), in(), both(), where(), dedup(), group(), project(), path() - and you build it up like a pipeline. It is more verbose than Cypher and more composable in code, because a traversal is an object you can pass around and extend. The steps that matter for correctness: dedup(), because traversals produce duplicates; limit(), on every step that could fan out; repeat().times() with an explicit bound; and barrier(), which forces evaluation and can dramatically change performance.
openCypher in Neptune is real and not complete. The query surface is substantial, and the gaps are specific - certain clauses, certain functions, and some behaviours around MERGE differ. The practical rule: check the current support documentation for every clause you depend on, and test it. Writing a query that works in Neo4j and discovering Neptune rejects it is a routine experience, and it is better discovered in Module 3 than in a migration.
SPARQL is declarative and set-oriented. Basic graph patterns, OPTIONAL, UNION, FILTER, MINUS, subqueries, aggregation, VALUES and property paths (foaf:knows+, which is SPARQL's variable-length traversal). Neptune's SPARQL support is good.
Transactions and isolation. Neptune provides ACID transactions with snapshot isolation for reads and read-committed-plus-conflict-detection semantics for writes: a write transaction that conflicts with a concurrent one fails with a ConcurrentModificationException and must be retried. So every write path needs retry handling, as in several other databases in this programme.
How a transaction is expressed differs by language: Gremlin over WebSocket supports explicit sessions; openCypher over HTTP treats each request as a transaction; SPARQL likewise. For multi-statement transactions in openCypher the practical answer is to express the whole unit of work as one query, which is a real constraint on how you structure writes.
The read-replica consistency model matters and is often missed. A read replica lags the writer by typically well under a second, and reads from it are eventually consistent. So a write followed immediately by a read through the reader endpoint may not see it. There is no bookmark mechanism as in Neo4j: the available answers are to read from the cluster endpoint when you need read-your-writes, or to tolerate the lag. Neptune does offer neptune-read-consistency on openCypher requests, which can request stronger consistency - check the current documentation, and measure your lag either way.
The engine-specific limitations to design around, which is this module's most useful content: no stored procedures or user-defined functions; no graph algorithms on the transactional engine; query timeout as the only real guard against a runaway traversal; connection limits tied to instance size; and some Gremlin and openCypher steps unsupported or behaving differently.
Laboratory exercise 3 - three languages, one service.
Build an identity resolution service and run at least 100 concurrent clients.
Implement the same five queries in all three languages where the model allows, and record the line count, the latency and - where available - the explain output for each. This comparison is the module's main artefact and is genuinely useful for a team deciding which to standardise on.
Demonstrate the openCypher gaps: take five openCypher queries that work in Neo4j and run them against Neptune. Record which fail, with the exact error, and the workaround for each.
Demonstrate the Gremlin duplicate problem: write a two-hop traversal without dedup() and with it, and record the difference in result count. Then do the same with limit() on an unbounded fan-out.
Implement a write that conflicts under concurrency, capture the ConcurrentModificationException, and implement a correct retry with backoff.
Measure the replica lag: write through the cluster endpoint and immediately read through the reader endpoint, 10,000 times, and record the miss rate. Then do the same reading through the cluster endpoint and show zero. That miss rate is the cost of reading from replicas.
Finally, measure the connection limit: open connections until they are refused, and record the number for your instance size.
Deliverable: the service, the five-query three-language comparison, the openCypher gap list with errors and workarounds, the dedup and limit demonstrations, the conflict exception with a working retry, the replica lag miss rate for both endpoints, and the measured connection limit.
# ==================================================================
# GREMLIN: imperative, composable. And four steps that matter.
# ==================================================================
%%gremlin
g.V().has('Person', 'email', 'ada@example.test')
.out('HAS_EMAIL', 'HAS_PHONE', 'HAS_DEVICE')
.in('HAS_EMAIL', 'HAS_PHONE', 'HAS_DEVICE')
.hasLabel('Person')
.where(neq('start'))
.dedup()
.limit(50)
.project('id', 'name')
.by(id).by('name')
# *** THE FOUR STEPS THAT MATTER FOR CORRECTNESS: ***
#
# 1. dedup() - TRAVERSALS PRODUCE DUPLICATES, one per path. Without
# it you count the same person several times, which is a
# CORRECTNESS bug, not a cosmetic one. Demonstrate it:
%%gremlin
g.V('p-0001').out().in().hasLabel('Person').count()
%%gremlin
g.V('p-0001').out().in().hasLabel('Person').dedup().count()
# -> 412 and 37. Both numbers mean something; know which you want.
# 2. limit() - on EVERY step that could fan out. Not just at the end:
%%gremlin
g.V().hasLabel('Person').limit(1000)
.out('HAS_DEVICE').limit(5000)
.in('HAS_DEVICE').limit(10000)
.dedup()
# An intermediate limit() bounds the work; a final one only
# bounds the result after the work is done.
# 3. repeat().times() - EXPLICITLY BOUNDED. The Gremlin equivalent
# of Neo4j's *1..3, and the same hazard if you omit the bound:
%%gremlin
g.V('p-0001')
.repeat(__.both('SAME_AS').simplePath())
.times(3)
.emit()
.hasLabel('Person')
.dedup().limit(100)
# simplePath() prevents revisiting nodes - without it a cycle
# makes the traversal much larger. until() is the alternative to
# times(), and WITHOUT EITHER the traversal does not terminate.
# 4. barrier() - forces evaluation of what has accumulated so far.
# It can change performance dramatically in both directions:
%%gremlin
g.V().hasLabel('Person').barrier(10000).out('HAS_EMAIL').dedup()
# Worth measuring rather than reasoning about.
# Gremlin's explain and profile:
%%gremlin
g.V().has('Person','email','ada@example.test').out().explain()
%%gremlin
g.V().has('Person','email','ada@example.test').out().profile()
# ==================================================================
# *** openCYPHER IN NEPTUNE: real, and NOT COMPLETE. ***
# ==================================================================
%%oc
MATCH (p:Person {email: 'ada@example.test'})
-[:HAS_EMAIL|HAS_PHONE|HAS_DEVICE]->(shared)
<-[:HAS_EMAIL|HAS_PHONE|HAS_DEVICE]-(other:Person)
WHERE other <> p
RETURN DISTINCT other.`~id` AS id, other.name AS name,
labels(shared)[0] AS via
LIMIT 50
%%oc
MATCH path = (a:Person {`~id`: 'p-0001'})-[:SAME_AS*1..3]-(b:Person)
WHERE a <> b
RETURN b.`~id`, length(path) AS hops
ORDER BY hops LIMIT 100
# Bounded, typed, anchored - the Neo4j discipline applies here too,
# and for the same reason.
# *** THE PRACTICAL RULE: CHECK THE CURRENT SUPPORT DOCUMENTATION
# *** FOR EVERY CLAUSE YOU DEPEND ON, AND TEST IT. ***
# The gaps are specific - certain clauses, certain functions, and
# some MERGE behaviours differ from Neo4j's. Writing a query that
# works in Neo4j and finding Neptune rejects it is a ROUTINE
# experience, and it is better discovered here than in a migration.
#
# The lab: take FIVE openCypher queries that work in Neo4j, run them
# here, record which fail with the exact error, and the workaround.
# Keep that list - it is the migration risk register.
# ==================================================================
# SPARQL: declarative, set-oriented, and good here.
# ==================================================================
%%sparql
PREFIX ex: <http://example.test/>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
SELECT DISTINCT ?other ?otherName ?via WHERE {
?p foaf:mbox <mailto:ada@example.test> .
{ ?p foaf:mbox ?via . ?other foaf:mbox ?via }
UNION
{ ?p foaf:phone ?via . ?other foaf:phone ?via }
?other foaf:name ?otherName .
FILTER(?other != ?p)
}
LIMIT 50
# PROPERTY PATHS - SPARQL's variable-length traversal:
%%sparql
SELECT ?b WHERE { ex:p-0001 ex:sameAs{1,3} ?b }
# or the unbounded forms, which carry the SAME HAZARD as `*`:
# ex:sameAs+ one or more
# ex:sameAs* zero or more
# Bound them, or rely on the query timeout - and the timeout is a
# backstop, not a design.
%%sparql
SELECT ?src (COUNT(?s) AS ?statements) WHERE {
GRAPH ?src { ?s ?p ?o }
} GROUP BY ?src ORDER BY DESC(?statements)
# ==================================================================
# TRANSACTIONS: ACID, with CONFLICT DETECTION you must handle.
# ==================================================================
# Neptune gives snapshot isolation for reads and conflict detection
# for writes. A write transaction conflicting with a concurrent one
# FAILS and *** MUST BE RETRIED: ***
#
# ConcurrentModificationException: Please retry the request.
#
# SO EVERY WRITE PATH NEEDS RETRY HANDLING, with backoff and jitter -
# as in several other databases in this programme.
#
# for attempt in 1..5:
# try:
# run_write()
# break
# except ConcurrentModificationException:
# sleep(min(2**attempt * 0.05, 2.0) * (0.5 + random()/2))
#
# HOW A TRANSACTION IS EXPRESSED DIFFERS BY LANGUAGE:
# GREMLIN over WebSocket -> explicit sessions are available
# openCYPHER over HTTP -> EACH REQUEST IS A TRANSACTION
# SPARQL over HTTP -> likewise
#
# *** SO FOR A MULTI-STATEMENT UNIT OF WORK IN openCYPHER, EXPRESS
# *** THE WHOLE THING AS ONE QUERY. *** That is a real constraint on
# how you structure writes, and it is better known than discovered:
%%oc
MERGE (p:Person {`~id`: $personId})
ON CREATE SET p.created_at = $now
MERGE (e:Email {address: $email})
MERGE (p)-[r:HAS_EMAIL]->(e)
ON CREATE SET r.since = $now
RETURN p.`~id`, e.address
# One request, one transaction, several MERGEs. The Neo4j MERGE
# discipline applies: identifying properties only, and nodes
# before relationships.
# ==================================================================
# *** THE READ-REPLICA CONSISTENCY MODEL. Often missed. ***
# ==================================================================
# A replica lags the writer by TYPICALLY WELL UNDER A SECOND, and
# reads from it are EVENTUALLY CONSISTENT. So:
#
# write via the CLUSTER endpoint
# read immediately via the READER endpoint
# -> MAY NOT SEE IT
#
# *** AND THERE IS NO BOOKMARK MECHANISM AS IN NEO4J. *** The
# available answers are:
# 1. read from the CLUSTER endpoint when you need read-your-writes
# 2. tolerate the lag, having measured it
# 3. openCypher's read-consistency header, where supported -
# CHECK THE CURRENT DOCUMENTATION, and measure either way
#
# curl -X POST https://<cluster>:8182/openCypher \
# -H 'Content-Type: application/x-www-form-urlencoded' \
# --data-urlencode 'query=MATCH (n) RETURN count(n)'
#
# MEASURE THE MISS RATE: write then immediately read via the reader
# endpoint, 10,000 times. Record the percentage. Then via the
# cluster endpoint: zero. *** THAT PERCENTAGE IS THE COST OF READING
# FROM REPLICAS in your deployment, and it is the number that makes
# the routing decision defensible. ***
# CloudWatch: NeptuneReplicaLag, NeptuneReplicaLagMaximum
# ==================================================================
# THE ENGINE-SPECIFIC LIMITATIONS. Design around these.
# ==================================================================
# * NO stored procedures, NO user-defined functions. The logic is
# in your application, always.
# * NO graph algorithms on the transactional engine. Neptune
# Analytics is a separate service (Module 5).
# * THE QUERY TIMEOUT IS THE ONLY REAL GUARD against a runaway
# traversal. There is no per-query memory cap as in Neo4j.
# * CONNECTION LIMITS TIED TO INSTANCE SIZE, and lower than you
# expect. MEASURE YOURS - open connections until refused:
# CloudWatch NumConnections / MainRequestQueuePendingRequestsCount
# * SOME Gremlin and openCypher steps UNSUPPORTED or DIFFERENT.
# * no triggers, no change-data-capture in the classic sense
# (Neptune Streams exists - check its availability for your
# engine version)
Discussion
No questions on this topic yet. Sign in to ask the first one.