Slide 49
Slide 49 text
def graph(conn, type !\\ nil, id, direction, options) do
n_type = if type do
":!#{type}"
else
""
end
conn
!|> Bolt.Sips.query!(
"""
MATCH (n!#{n_type})
WHERE id(n) = toInteger({id})
!#{graph_optional_match(direction, options)}
WITH !#{graph_with(direction)}
RETURN !#{graph_return(direction)}
""",
cypher_parameters(id, options)
)
!|> graph_return_to_map()
end
To construct the graph, we have to match on the starting node, which is looked up by id. You’ll notice we look up the node id by using the id function. This is because
ids in Neo4j cannot be looked up with dot id, like in SQL. We have to explicitly cast to ToInteger because parameterized values aren’t cast automagically like in Postgres.
Next we’ll figure out the direction of the graph by taking in the direction of either forward, backward, or both. Users may not care about the backwards graph, because
they only care about how the thing they made is used, but if you’re making a sweater out of handspun yarn and run out of yarn when you haven’t finished the sweater,
you’ll want to be able to look up where to source that material.
With, in cypher queries, can be tricky. With is a hard line in the sand - only names declared as outputs can be used after the with. Any pre-existing named variables are
completely hidden after the with line. With doesn’t have to be the last line before return, it can be used as filtering to break up multiple sub-queries. The trickiness of
with is why there is only one with line in this query - I tried having a with for each direction but the values couldn’t all be used in the return, which lead to problems.