examples · graph · 5 / 17
5. dijkstra - weighted shortest path
← Graph exampleswhat this does
dijkstra returns the total cost of the cheapest path from src to dst under your edge weights, and null when the destination is unreachable. GET /v1/tenants/:t/graph/:schema/dijkstra takes rel, src, dst and weights_json.
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 the top-K cheapest paths instead of a single shortest, use the k-shortest endpoint - loop-free paths in increasing weight.
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.