There are a couple of ways to achieve this, depending on what you want to return (or how the queries are nested), but either way, either SHORTEST_PATH
or K_SHORTEST_PATHS
will be your friend. Here is an example:
FOR v,e IN INBOUND SHORTEST_PATH start_node to root_node
GRAPH 'named_graph'
RETURN e
Referencing the SHORTEST_PATH docs, we can start to break this down.
- We are finding a path (the shortest path by the number of hops or "weight") from a "start" node to an "end" node.
- Using
INBOUND
or OUTBOUND
will depend on how your graph/data-model is built.
- The
v,e
variables represent "vertices" and "edges" (v
and e
, respectively) found along the path.
This query pattern can then be used to calculate the number of vertices or edges, like so:
FOR start_node in child_collection
FOR root_node IN root_collection
LET edges = (
FOR v,e IN INBOUND SHORTEST_PATH start_node to root_node
GRAPH 'named_graph'
RETURN e._id
)
RETURN {
root: root_node._id,
child: start_node._id,
pathLen: LENGTH(paths)
}
This may be a bit basic (there are likely ways to optimize this), but it shows how you can use a variable to hold a sub-query, using those results to calculate a path length.
Alternately, you can use K_SHORTEST_PATHS to do this calculation for you. For instance, the previous query could be reduced to this:
FOR p IN INBOUND K_SHORTEST_PATHS start_node to root_node
GRAPH 'named_graph'
OPTIONS { weightAttribute: 'weight' }
LIMIT 1
RETURN p
Which finds the first shortest path between two points. Here, we use LIMIT 1
to make sure we only return one path. The result will be something like:
[
{
edges: [ ... ],
vertices: [ ... ],
weight: <number>
}
]
Or you can customize the return to better meet your needs. Do not return data you don't need or won't use.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…