examples · graph · 5 / 7
5. dijkstra - weighted shortest path
← Graph exampleswhat 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"weights = {
"o001|p014": 1.0,
"p014|u091": 0.5,
"u091|p001": 2.0,
}
result = db.graph.dijkstra(
"shop.orders",
rel="bought_product",
src="o001",
dst="p001",
weights=weights,
)const weights = {
"o001|p014": 1.0,
"p014|u091": 0.5,
"u091|p001": 2.0,
};
const result = await db.graph.dijkstra("shop.orders", {
rel: "bought_product",
src: "o001",
dst: "p001",
weights,
});weights := map[string]float64{
"o001|p014": 1.0,
"p014|u091": 0.5,
"u091|p001": 2.0,
}
result, _ := db.Graph().Dijkstra(ctx, "shop.orders", originchain.DijkstraRequest{
Rel: "bought_product",
Src: "o001",
Dst: "p001",
Weights: weights,
}) 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_jsonfall 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-urlencodeor your SDK's helper rather than concatenating into the URL.