OriginChain docs
examples · graph · 5 / 7

5. dijkstra - weighted shortest path

← Graph examples
what this does

Finds the minimum-cost single path from src to dst using your edge weights. Returns the total cost. If the destination is unreachable, returns null.

when to use it
  • Routing / cost minimisation - latency, price, distance.
  • "Cheapest connection" answers where edges aren't equally costly.
  • When BFS hop-count isn't the right metric, but you still only need one path.
schema requirement

The relation must be declared in the schema's [[relations]] block. See schemas/reference#relations.

the request

weights_json is a URL-encoded JSON object keyed by "src|dst" with a numeric weight. An empty {} means "every edge weighs 1" and Dijkstra degenerates to shortest hop-count.

GET /v1/tenants/:t/graph/:schema/dijkstra?rel=...&src=...&dst=...&weights_json=...
WEIGHTS='{"o001|p014":1.0,"p014|u091":0.5,"u091|p001":2.0}'

curl -G "https://$OC_HOST/v1/tenants/$OC_TENANT/graph/shop.orders/dijkstra" \
  --data-urlencode "rel=bought_product" \
  --data-urlencode "src=o001" \
  --data-urlencode "dst=p001" \
  --data-urlencode "weights_json=$WEIGHTS" \
  -H "Authorization: Bearer $OC_TOKEN"
what you get back
{ "cost": 3.5 }

One field: cost: number | null. null means no path exists. The endpoint returns the cost only - if you need the path itself, use all_simple_paths.

how it works
  • Classic Dijkstra over a min-heap, expanding the cheapest frontier node.
  • Edges missing from weights_json fall back to a weight of 1.
  • For top-K paths instead of a single shortest, use the k-shortest endpoint (different route).
common mistakes
  • Negative weights. Dijkstra assumes non-negative edges. Negative weights produce undefined results - reformulate as a positive cost, or pick a different algorithm.
  • Forgetting to URL-encode weights_json. The JSON contains {}, quotes, and the | separator - use --data-urlencode or your SDK's helper rather than concatenating into the URL.