We give the relationships of smollerGraph's social graph a weight, as LDBC's Social Network Benchmark does in its cheapest path question, and find the path whose weights add up to the least, with Dijkstra's algorithm. A priority queue hands out the cheapest node left, which can't get any cheaper, so the search settles the nodes in the order of their cost. From one end, it settles most of the graph, so it runs from both ends, and we work out when it can stop. Cypher gets WSHORTEST, the way Kùzu writes a cheapest path, and the page draws each relationship's weight. It's a vanilla version of what Neo4j's libraries and Kùzu offer, written to see how it works.
Topics: Cypher, Graph algorithms, Visualization
The code
Each step on screen is a tag in the database's repository. The code at the end of the episode is ep013/end.
Transcript
Intro
0:00 Welcome back, and in episode thirteen, we're going to give smollerGraph's relationships a cost, and find the path whose costs add up to the least, with Dijkstra's algorithm. Before we build it, let's see where it's going.
0:13 By the end, smollerGraph is going to find the cheapest path between two people, in a social graph where each friendship has a weight. We run it, and the page draws a path of ten hops, with the weight of each friendship on it, mostly ones and twos, a path that costs sixteen in all.
0:31 On the series' website, there's more about the project, and where it's heading. The code is open source, on GitHub, and tagged at each step of each episode, so you can follow along from any point. And each episode has a page, with its chapters and the code it goes through.
Last time
0:48 A quick reminder of where we left off, first. smollerGraph learned to find a shortest path, with a breadth-first search that keeps the relationship that first reached each node. On our social graph, a search from one end reached nearly everyone, so the search went from both ends, and the two met in the middle. Cypher got shortest path, as Neo4j writes it, and the page drew the path. But a shortest path counts hops, and treats each relationship as if it cost one. Today, each relationship gets a cost of its own.
Today
1:21 Today's plan has four parts, from the data up to the page. Our friends graph is going to get a weight on each friendship, the way LDBC's benchmark weighs them. Then we write Dijkstra's algorithm, which finds the path whose weights add up to the least, with a priority queue. Like last time, we make it search from both ends, and this time, knowing when to stop takes a little more thought. And Cypher gets a way to ask for it, and the page draws the weights. Right, let's start with why the path with the fewest hops isn't always the one we want.
Why weights
1:56 A hop is a fair cost when each relationship is as good as any other, and in many graphs, it isn't. On a road map, a road has a length, or a time it takes to drive, and a route through three short roads beats one long one. In a computer network, routing protocols such as OSPF give each link a cost, and send packets along the cheapest way, not the fewest links. And version two of LDBC's interactive workload asks for a cheapest path between two people, in place of a shortest one. Each friendship's weight there depends on how many messages the two people have exchanged, so a path through people who talk a lot is cheaper. The path whose weights add up to the least is the cheapest path, and it can have more hops than the shortest one. The paper that describes the workload says that cheapest paths are what Dijkstra's algorithm solves.
Weights
2:47 The weights start in make friends, which writes our social graph. Its comment at the top adds that the facts have a weight on each friendship now, beside the CSV files that Neo4j and Kùzu can import. We include algorithm, for max, and cmath, for the square root. Messages is a second random generator, a Mersenne twister with a fixed seed, seven. The comment over it says why: the messages two friends have sent each other come from a generator of their own, so the people each person knows are the ones they knew. That keeps the paths from last episode as they were. LDBC weighs a friendship by the messages the two people have sent each other, and we have none, so for each friendship, sent is a made-up number of them, from one to sixteen hundred. The weight is the one LDBC's paper gives: forty, less the square root of the messages, rounded, and at least one. Its comment says it's the weight that LDBC's Social Network Benchmark gives a friendship in its cheapest path question, the more messages, the cheaper, from thirty-nine for a single one down to one. The square root makes the first messages count the most. The facts get the weight in braces, as a property of the relationship, and the CSV files for the other databases stay as they were. To follow a weight, the graph has to read a relationship's property by its key. In the graph's header file, Find relationship property returns a relationship's value for a key, such as its weight, as its comment says, as a node's would. In the private part, Lookup is going to be the loop they share, and its comment says it returns the value of a key in the chain of properties that starts at an id, if the chain has it. In graph, Find property keeps its first lines, as a node's name is in its record, and hands the rest to Lookup, with the node's first property. Find relationship property reads the relationship's record, and hands Lookup its first property. Lookup is the loop that was in Find property: from the first id, it reads each record of the chain, and returns its value when its key is the one asked for. In the graph's tests, the fox's EATS relationship, in the test that reads properties in braces, has a source, Wikipedia, which Find relationship property finds. And it has no weight, which comes back as nullopt.
4:57 Let's build it, with the weights in make friends, and run the tests. All fifty-eight of them pass, with the new checks in the test for properties. Then we write the friends again, a hundred thousand people who each know ten others, with a million friendships between them. With sed, here are the first friendships, after the people's lines, each with its weight in braces, eleven, seven and ten. Loading them takes a little longer than it did, as each friendship gets a property record too, and the folder shows what that costs. The properties file is sixty-four megabytes, a record of sixty-four bytes for each weight, more than twice the size of the relationships. A weight is eight bytes, so most of each record is the room for a key and a string, which a number doesn't need.
Dijkstra
5:41 Dijkstra's algorithm, from nineteen fifty-nine, is a breadth-first search where the frontier is ordered by cost, not by hops. It keeps the nodes it has reached in a priority queue, a structure that hands out the cheapest of them first, each with the cheapest cost found to it so far. It starts with the start, at a cost of zero. Each round, it takes the cheapest node out of the queue. That node is settled: no other path can reach it more cheaply, as any other path has to leave through a node in the queue that costs at least as much already, and the weights are zero or more. Then it looks at each of the node's neighbours. When going through this node costs less than the cheapest cost the neighbour had, the neighbour gets the new cost, and this node as its parent, and goes into the queue. When the end comes out of the queue, it's settled, and its cost is the cheapest. The path is read back through the parents, as last time. A negative weight would break the argument, which is why the algorithm needs weights of zero or more.
6:41 In query's header file, we include cstdint, for the cost, a sixty-four-bit number. The path gets a cost, its relationships' weights added up, which is zero by default, and the comment over the struct adds that a cheapest path has its cost too. Cheapest path takes what Shortest path takes, and the key of the property that holds the weight. Its comment says it returns a cheapest path between the two nodes, along relationships of the type, followed in the direction: one whose weights, the property key, add up to as little as any other's, found with Dijkstra's algorithm. And a relationship without a weight that's a whole number of zero or more isn't followed, as Dijkstra's algorithm can't use it. Path text's comment adds that each relationship gets its properties in braces, so we can see the weights. In query, we include cstdint, functional, for std greater, queue, for the standard library's priority queue, and variant, to read a property's value. In the unnamed namespace, Weight reads a relationship's weight. It looks the property up by its key, and when it's there and holds a whole number, with get if, it's the weight, unless it's below zero, and otherwise there's no weight. Its comment says it's the relationship's weight when it's a whole number of zero or more, as Dijkstra's algorithm needs. Literal is for the path's text, and its comment says it writes a property's value as Cypher writes it: a string in quotes, and a number as it is. When the value holds a string, it goes between single quotes, and otherwise it's the number, as text. Then comes Cheapest path, whose signature is Shortest path's, with the weight's key at the end. Costs is an unordered map from each node the search has reached to its cost, and the start costs zero. The comment over it says that's the cheapest cost found so far to each node reached, which can go down until the node is settled, and the hop that gave it. The parents keep the hops, as they did in the breadth-first search. Entry is a pair of a cost and a node, cost first, as pairs compare their first values first. The queue is a priority queue of entries, and its comment says why it takes std greater: a priority queue keeps its greatest at the top, and std greater turns that round, so the top is the least. The start goes in at zero, and while the queue has entries, it takes the top one, the cheapest, with a structured binding, which names the pair's two values, cost and node. A node goes into the queue again each time its cost goes down, and the entries with its old costs are skipped, as the comment says, as they cost more than its cost now. A standard priority queue can't lower an entry's cost in place, so that's the usual way round it. When the end comes out, the search can stop, and the comment over that says why. The cheapest of the nodes left can't get any cheaper, as the weights are zero or more, so the end is settled once it comes out. Then the path is read back from the parents, gets the end's cost, and goes back with the number of nodes that have a cost, the nodes reached. Otherwise, for each hop from the node, it reads the relationship's weight, and skips a relationship without one. The cost through this node is its cost plus the weight. Try emplace adds the neighbour with that cost, when it's new. When it isn't, and the cost through here is no cheaper than the one it has, the hop is skipped. Otherwise, the neighbour's cost goes down to the new one, its parent becomes this hop, and it goes into the queue at its new cost. When the queue runs out, there's no path. Path text reads each relationship's properties, and writes them in braces, a key, a colon and its literal, with commas between them, after the type.
10:20 In main, the usage line for sg path gets an optional weight key, in square brackets. Find path's comment says that with a weight's key, it finds a cheapest path, and it takes the key as a character pointer, which is null without one. Search is a shortest path when there's no weight, and otherwise a cheapest path, with the weight's key. When there's a path and a weight, it prints the path's cost too, after its hops. In main, path takes six or seven arguments now, and passes the seventh on as the weight, when there is one, and null otherwise. In the path tests, Takes the cheaper way with more hops builds a small graph of five people, from facts in a string, a relationship a line. Ada knows Dee, with no weight, Ada knows Bob at thirty, and Bob knows Dee at one. Ada knows Cy at two, and Eve knows Cy at three, and Dee at four. The comment over them says what that makes: Ada knows Dee with no weight, and through Bob, at a cost of thirty-one, or through Cy and Eve, at nine. That one needs Cy's relationship with Eve, which points from Eve to Cy, followed backwards. The test loads the facts into a graph, and finds Ada and Dee by their names, for the searches. The cheapest path from Ada to Dee, both ways, which the test checks as the path's text, goes through Cy and Eve, against the arrow from Eve to Cy, and costs nine. That checks the weights, the direction, and that the relationship with no weight is left out. Following the arrows, the way through Cy is cut, and the way left is through Bob, at thirty-one. The last check is the shortest path, which is Ada to Dee, in a single hop. Its comment says the shortest path takes the relationship with no weight, which the cheapest path can't add up, so the cheapest path doesn't follow it.
12:04 With the weighted friends loaded, let's run the tests. All fifty-nine of them pass, the cheapest path's among them. First, the shortest path between our two people from last episode, which now shows the weights. It's five hops, and its weights are twenty, twelve, seven, thirty-six and eight, which add up to eighty-three. Then the cheapest path, with the weight's key, which runs Dijkstra's algorithm from one end. It's ten hops, twice as many, through friends who talk a lot, with weights of ones, twos and threes, and a cost of sixteen. But the search reached all hundred thousand people, read about twenty-three thousand pages, the properties file among them, and took about three hundred and fifty milliseconds.
Both ends
12:45 From one end, Dijkstra's algorithm settles each node cheaper than the end, which for our two people is about half of the graph, and it reaches the rest on the way. So, like last time, we search from both ends. The start's side settles nodes from the start, and the end's side from the end, following the relationships backwards, and each round, the side whose next node is cheaper takes it. When a side lowers the cost of a node that the other side has reached, there's a way from one end to the other through that node, and we keep the cheapest of those. But unlike a breadth-first search, the first meeting isn't necessarily the cheapest, as a cheaper way can still turn up through nodes neither side has settled. So the search stops when the two sides' next costs add up to the cheapest way found. Any path through nodes neither side has settled costs at least those two next costs, so there's nothing cheaper left to find.
13:40 In query, we include limits, for the largest sixty-four-bit number, which stands for no way found yet. Entry and Queue move out of Cheapest path, into the unnamed namespace, as both sides need a queue. Their comment says the queue holds the nodes a search has still to settle, each with the cost it was put in with, cheapest first. A priority queue keeps its greatest at the top, and std greater turns that round, so the top is the least, as it did before. Queue is the priority queue's type, so that a side can name it. Weighted side is one end of a search from both ends, like the breadth-first search's side, with costs and a queue in place of a frontier. Its comment says what it holds: the direction it follows relationships in, and the cheapest cost it's found to each node it has reached, which can go down until the node is settled. Then the hop that gave it, and the nodes it has still to settle. Next cost's comment says it returns the cost of the next node a side settles, or nothing once it has settled all it can reach. A node goes in the queue again each time its cost goes down, so the entries with its old costs are dropped from the top first. So while the queue isn't empty, and its top entry costs more than its node's cost, the top is popped. Then an empty queue gives nothing, and otherwise it's the top's cost. Settle is given the graph, the type, the weight's key, both ends of the search, and the best way so far with its meeting node, which it can change. It pops the side's cheapest node, and goes through its hops, with the loop from our first version, on the side's direction, costs and parents. It reads each weight, skips a relationship without one, and adds the weight to the node's cost. When the neighbour is new, or that's cheaper than the cost it has, it lowers its cost, sets its parent, and pushes it, as before. What's new is at the end of the loop, after the push. When the other side has a cost for the neighbour, the way from end to end through it costs the two added up. When that's less than the best so far, it becomes the best, and the neighbour is where the two halves meet. The comment over Settle says so: a neighbour that the other side has reached is a way from one end to the other, and best keeps the cheapest of those, with the node where its halves meet. In Cheapest path, the old search goes, and two sides take its place, with designated initialisers, which name the fields they set. The start's side follows the direction we're given, from the start at zero, and the end's side the reversed direction, from the end at zero. The queue is left out, as each side's queue starts empty, and each gets its first entry with push. Best starts at the largest number, which no path costs, and meet at the start. The loop's comment says each round settles a node of the side whose next one is cheaper. A path through nodes neither side has settled costs at least the two next costs added up, so once they add up to the best way found, there's no cheaper. So each round, it gets the two sides' next costs, and stops when either side has run out, or when the two add up to the best way found or more. Otherwise, the side whose next node is cheaper settles it. Settle takes the moving side first, then the other side, so for the end's side, the two swap places. The nodes reached are the nodes in both sides' costs, and with no best, there's no path. Otherwise, the path is joined from the two halves at the meeting node, as in last episode's search: the start's half up to the meeting node, then the end's half reversed, without the meeting node a second time. Its cost is the best, and it comes back with the nodes reached.
17:11 With the friends loaded again, on this step's code, let's run the tests. All fifty-nine pass, and the cheapest path test finds its path of nine from both ends. Then the cheapest path between our two people again. It's the path we found before, ten hops at a cost of sixteen, and the search reached about forty-eight hundred people, not a hundred thousand. It read about forty-eight hundred pages, in about six milliseconds, which is about sixty times less time. I checked it against the search from one end on a hundred and fifty pairs of people, and the two agree on each cost.
WSHORTEST in Cypher
17:47 For Cypher, Neo4j and Kùzu go two different ways again. Neo4j's Cypher has no cheapest path, so you call a procedure, from the Graph Data Science library, which copies the graph into memory first, or from APOC, a library of procedures that runs on the stored graph. Kùzu writes it in the relationship, as it does for shortest paths: a star, then W SHORTEST, and the weight's key in brackets, and cost of the relationship's variable returns what the weights add up to. Our relationships have no variables, so we're going to take Kùzu's way of writing the relationship, and return the cost with cost of the path's variable, next to length of p. Like last time, ours is a vanilla version, to see how it works, and it isn't going to scale the way theirs do.
18:31 In the parser's header file, a relationship pattern gets a weight, the property a cheapest path adds up, as its comment says, written W SHORTEST and the weight in brackets, which is how Kùzu writes it. A return item's comment adds functions of the path, length of p, how many relationships it has, or cost of p, what its weights add up to. So length, which was true or false, becomes function, the function's name, or empty for none. The query's comment adds that a path can be written as p equals a pattern in brackets, for a cheapest path, and shortest says whether it's in shortest path. In the parser, the grammar says that the variable and its equals sign come before a pattern on its own, or before shortest path. Parse query reads the variable and the equals sign as before, and then shortest is whether the keyword shortest path follows, and its opening bracket is read when it does. Its closing bracket is read after the pattern, when it had one. The grammar for a relationship adds W SHORTEST and a key, after the star. When the star has no number after it, the hops are any, as before, and then when the keyword W SHORTEST follows, the parser reads an opening bracket, a word, which is the weight's key, and a closing bracket. The comment over it adds that W SHORTEST after the star names the weight a cheapest path adds up. The grammar for a return item adds cost to length, and Parse return item reads either of them as the function's name, and fails with what it expected, length or cost, otherwise, and then the opening bracket follows. In the parser's tests, Reads a shortest path checks the function's name, length, in place of true. Reads a cheapest path parses our path from Ada to Dee, with W SHORTEST and the weight, and returns the path and its cost. It checks the path's variable, that it isn't a shortest path, the relationship's any hops, its weight's key, and that the second item is the cost. In Says what it expected, a path written without shortest path isn't an error any more, so that line gets W SHORTEST without its brackets, which fails where the opening bracket should be.
20:33 In the plan's header file, a step gets a new kind, cheapest path, which its comment says does what a shortest path step does, for a cheapest path, whose relationships' weight adds up to the least. A step gets the weight's key, with an empty string by default. The braces after it give it a default, so the steps written without it, which list their fields in order, don't get a warning for a field they leave out. The column's comment says now that with no slot, it can be a function of the path, its length or its cost, and the length flag becomes a function's name. The cell's comment says a path, or a function of it, comes with the path and its first node. In plan, Add returns's comment for a path adds that a shortest path counts hops, so it has no cost. Asking for the cost of a shortest path is an error, and its message says that it counts hops. The column's heading is the function's name, with the variable in brackets, or the variable when there's no function. A node's variable can't have a function either. In plan query, the error for a path's pattern says a path now, as it can be a cheapest one. A path is a shortest one, or with a weight, a cheapest one, as the comment says, so a path with both or with neither is an error, which says it needs shortest path or W SHORTEST. The step after the two finds is a shortest path step, or a cheapest path step, depending on shortest, with the relationship's type and its direction as before, and its weight. That's all the planner needs, as both kinds of path find their two ends with Add find. In Run, the two kinds of path share a case, so the code that keeps the row is written once. Each runs its search between the row's two nodes, which it names from and to, Shortest path or Cheapest path with the weight's key, and keeps the row when there's a path. When the rows become cells, a column for the cost gives the path's cost, as a number. In Explain, a cheapest path is written with its type, the star, W SHORTEST and the weight in brackets. In the plan's tests, Finds a cheapest path with a weight checks the plan from Ada to Dee, with W SHORTEST and the weight, which returns the cost. The plan is two seeks, one for each name, and then the cheapest path step, with W SHORTEST in it, as EXPLAIN writes it. A path written with neither shortest path nor a weight is an error that says what it needs, and so is asking for the cost of a shortest path, as it counts hops. Then a run test, with weighted facts of its own, as the fixture's food chain has no weights. Ada knows Bob at thirty, and Bob knows Dee at one, while Ada knows Cy at two, and Cy knows Dee at three. Both ways are two hops, so a shortest path could take either. The query asks for the cheapest, by weight, from Ada to Dee, and returns the path, its length and its cost. The answer goes through Cy, with each weight in braces, its length, two, and its cost, five.
23:26 Let's build it, with W SHORTEST in the parser, and run the tests. All sixty-two of them pass, with the three new ones. With the friends loaded, let's ask for the plan of a cheapest path between the second and the third of our thousand people. It finds both in the index, and then runs the cheapest path step between them, with W SHORTEST and the weight. Then we run it, without EXPLAIN, and it returns the path's length and its cost, in a single row, for this pair of people. The cheapest path between them is seven hops long, and costs sixteen.
Weights on the page
24:00 The page draws a relationship as a line and an arrow, and a cheapest path is worth little without its weights. In the API's header file, the comment on query JSON adds that the relationships come with their properties. In the API, each relationship it sends gets its properties, as a JSON object, with Properties JSON, which the inspector's chains use already. The API's tests expect an empty object of properties on each relationship of the animals, which have none. That's in both tests that check what the page draws: the one that answers with rows, and the one that draws a path. Each relationship gets its properties after its type, so each line of the expected JSON grows by a field. In the view, the comment over draw adds the relationships' properties, which are drawn when the names are. After the names, the fill becomes the relationships' coral, and the comment over it says what's drawn: the values of a relationship's properties, such as its weight, at its middle, in the relationships' coral. For each relationship, its properties' values are joined with commas, and a relationship without any is skipped. The text goes at the middle of the relationship, halfway between its two nodes, with a stroke of the background's colour first, as the names have, so it reads over the line. The values alone keep it short, as weight and a colon on each line covered the names. In app, expanding a node draws its relationships from its record's chains, and each now passes its properties on too, out and in. The page serves the Wikidata graph, which has no weights. So the friends override is a second file for Compose, which changes what the first one says. Its comment says what it serves: the friends graph from the benchmarks, with a weight on each friendship, in place of the mammals and birds, with Compose up and both files. It changes the database's command, so the container writes the friends with make friends, loads them, and serves them. And the Docker ignore file leaves the graphs and the benchmark's data on the machine out of the image, as they're made in the container.
25:57 In the browser, with the friends served from Compose with both files, the page opens on its usual query about the dog family, which finds nothing in this graph. Let's ask for the cheapest path between the second and third of our people, with its cost. It takes a few seconds to type, and it's the query we ran in the terminal. We run it, and the page draws the path, with each friendship's weight in coral, halfway along it. The table has the path as Cypher writes it, with the weights in braces, and its cost, sixteen.
What's missing
26:30 Our cheapest path leaves a few things out. On a map, a search can guess how much is left, from the distance as the crow flies, and A star uses that guess to settle the nodes towards the end first. On a social graph, the guess has to come from somewhere else, such as distances worked out ahead of time. A negative weight breaks Dijkstra's algorithm, and Bellman-Ford handles it, at a higher cost. Each weight is a property record of its own, read through the relationship's chain, where a weight kept next to the relationship would save a read for each hop. And the Graph Data Science library copies the graph into memory, in a form made for algorithms, before it runs them, which is a different trade from ours. Keep in mind that this is a vanilla version of what Neo4j's libraries and Kùzu offer. Theirs are built for graphs far bigger than ours, with years of engineering behind them, while ours is there to show how a cheapest path is found.
Wrap-up
27:27 So, today smollerGraph learned to find a cheapest path. Each friendship got a weight, as LDBC weighs them, kept as a property of the relationship. Dijkstra's algorithm settles the cheapest node left each round, from a priority queue, so the end's cost is the cheapest once it comes out. From both ends, the search stops once the two sides' next costs add up to the cheapest way it has found, and it reached about twenty times fewer people. Cypher takes W SHORTEST, as Kùzu writes it, and cost of p, and the page draws each weight, a vanilla version of what Neo4j's libraries and Kùzu offer.
28:06 This is going to be an evolving project, so I'd love to hear from you. Let me know in the comments what you'd weigh the relationships of your own graphs by, and if you'd like to follow along, subscribe to the channel. I hope you find this useful, and thanks for watching.