We teach smollerGraph to follow a relationship backwards, from the node it ends at. Its records are full, so labels and relationship types become tokens, as in Neo4j: numbers kept in place of their names, which are kept once each in a store of their own. That makes room for a second chain of relationships for each node, those that end at it. Cypher gets relationships that point left, the planner starts from whichever node is cheapest to find and expands both ways from it, and the page shows both chains. Then we make the benchmark against Neo4j and Kùzu fair: all three answer two questions in Cypher, parsing and planning along with the rest, one following relationships out of a person and one following them in.
Topics: Storage and indexes, Cypher, Performance
The code
Each step on screen is a tag in the database's repository. The code at the end of the episode is ep011/end.
Transcript
Intro
0:00 Hello and welcome back to episode eleven, where we're going to teach smollerGraph to follow a relationship backwards, from the node it ends at, and to start a query from whichever of its nodes it can find most quickly. Let's begin with a quick look at where we're going to be by the end of the episode.
0:17 By the end, smollerGraph is going to answer questions about a family of animals by starting from the family. This query asks for the species of the cat family, Felidae, with their genera, which the page draws around the family. The line at the bottom says it took a fraction of a millisecond on the server. And the plan finds Felidae by its name, and follows its relationships backwards, down to the genera and their species.
0:42 On the website of the series, you can find more information about the project. The code is open source on GitHub, tagged at each step of each episode, so that you can follow along, and each episode has a page here, with its chapters and its code.
Last time
0:57 Now, before we get to today's work, let's quickly go over what we did last time. Nodes and properties got records of sixty-four bytes, with room for real names, and nodes got a label, which our facts and our Cypher learned to read. Then we loaded the mammals and birds on Wikidata, about twenty-two thousand taxa, from each species up to its class. And the page draws what a query returns on a canvas, and says what each query cost. But a node keeps the relationships that start at it, and no others, so finding the species of a family means going through each species, to see where its relationships lead. Today, smollerGraph learns to follow them the other way too.
Today
1:37 Today, we go from the records on disk up to the planner, and then to a benchmark. Our records are full, so labels and relationship types become tokens, numbers that stand for their names, which makes room in them. With that room, each node gets a second chain, of the relationships that end at it. Cypher gets relationships that point left, and the planner starts from whichever node of a pattern it can find most quickly, and walks from there both ways. Then we make our benchmark against Neo4j and Kùzu fair, with all three asked two questions in Cypher. All right, let's get started with a question our graph answers slowly today.
One way
2:17 mvGPT, the GPT from the other series on this channel, has started asking smollerGraph for facts. In its episode twenty-four, one of the questions it learned to ask is which species in a family are critically endangered, such as in Manidae, the family of pangolins. On last episode's code, with the Wikidata graph loaded, let's ask for the plan of that query, with EXPLAIN. It starts with a label scan of the species, about seventeen thousand of them, and keeps the critically endangered ones. Then it walks two hops up from each of those, to see whether it reaches Manidae. Then we run it, and three pangolins come back, after reading more than thirteen hundred pages. The family is a single node, which the index finds in a few page reads. But a node keeps the relationships that start at it, so a plan can't go from the family down to its species.
Neo4j and Kùzu
3:08 Neo4j and Kùzu can both follow a relationship from either end, and they go about it in two different ways. Neo4j's record format puts each relationship in two chains, one for the node it starts at, and one for the node it ends at, with links to the previous and the next relationship in each. A node keeps the first of its chain, which holds its relationships both ways. A node with a lot of relationships gets them split into groups, by type and by direction, so a walk doesn't step over the ones it doesn't want. Kùzu keeps its adjacency in compressed sparse row form, as we saw in episode one, and it keeps it twice, once in each direction. So a walk backwards reads the backward copy, which is sorted by the node relationships end at. Our relationships are in chains already, so we're going to stay close to Neo4j. Each relationship goes into two chains, and each node keeps the first of both, one for the relationships out of it and one for those into it, so a walk one way doesn't step over the other.
Making room
4:09 For a second chain, each node needs the id of the first relationship that ends at it, and each relationship needs the id of the next one into the node it ends at. That's four bytes more for each record, and neither has four bytes to spare. A node's sixty-four bytes are its name, forty-four of them, its label, twelve, and the ids of its first relationship and its first property. A relationship's thirty-two bytes are its type, sixteen of them, its two nodes, the next relationship out of its start, and its first property. Both spend a lot of their bytes on a name that a lot of records share. About seventeen thousand of our taxa have the label Species, and each relationship has the type PARENT_TAXON. So, like Neo4j, we're going to keep each label and each type once, in a store of tokens, and give a record the token, a four-byte number, in place of the name. A node's name gets forty-eight bytes, then come its label's token and its three ids, first out, first in and first property, which is sixty-four bytes again. And a relationship becomes its type's token, its two nodes, its next relationship out, its next relationship in, and its first property, twenty-four bytes, a quarter less than it was.
5:21 The tokens go in a class of their own, the token store, starting with its header file. In the header, after its guard, we include cstddef and cstdint, for sizes and fixed-width numbers, then functional, for std less, which comes up at the bottom. Map is for a sorted map from names to tokens, optional for a token that may not be there, and string, string view and vector are for the names. Then Abseil's status, for when a file can't open, and our record file, from episode two, as a token's name is going to be a record too. In our namespace, Token ID is a thirty-two-bit number, like the ids of nodes and relationships. A token is a number that stands for a name many records share, such as the label Species, so a record keeps four bytes in place of the name. K no token is all ones, inline constexpr, so the compiler knows its value, and each file that includes the header shares one definition of it. It's the token for no name, such as the label of a node that hasn't got one. Token record is a token's name on disk, and its comment adds that its id in the file is the token, so finding a token's name needs no search. The name gets thirty-two bytes, and a page holds a hundred and twenty-eight of them. Then the token store class, which keeps names and the tokens that stand for them, in a file of records, and in memory both ways, as there are few of them. Neo4j keeps its labels and relationship types in stores like this one. K max name is the longest name a token can stand for, thirty-one bytes and the zero at its end. Open opens the store in the file at a path, creating it when it isn't there, and Open temporary uses a file with no name, for the tests, as the record file does. Flush writes its changed pages, and page reads and page writes count them, as the other files do. Add returns the token for a name, adding it the first time, and the name has to fit in k max name bytes. Find returns the token for a name, if the store has one, without adding it. A query looks names up with Find, so a query that asks about a type nobody has used doesn't add that type to the store. Add is for the facts we load, which bring new labels and types with them. Name goes the other way, from a token to its name, and its comment adds that k no token gives nothing, an empty name, with the conditional operator. In the private part, Load reads the file's names into memory, once the file is open. Then come the record file and the two directions in memory, and their comment says what they hold: each token's name, in a vector, where the token is the index, and each name's token, in a map. The map's third argument, std less with nothing in its angle brackets, makes its comparisons transparent, so Find can look up a string view without making a string out of it first. In the token store, we include algorithm, for min, and cstring, for the memory functions. Open opens the record file at the path, and once it's open, loads its names into memory. It returns the status either way, so an error opening the file goes back to the graph, which stops opening its other files, and Open temporary does that for a temporary file. Load empties both directions, then reads each record, from token zero up to the file's count. Each name goes on the vector, and into the map with its token. A graph with a few labels and types reads a page or two here when it opens. Add looks the name up first, and returns the token it has, if it has one. Otherwise, it fills a record with zeros, copies the name in, cut short at k max name, and appends it to the file, whose new id is the new token, and the name goes into memory, both ways. Find looks the name up in the map, and returns its token, or nullopt when there isn't one. So with the names in memory, neither Add nor Find reads a page of the file, and a lookup costs a few string comparisons, as a map is a sorted tree. A hash map would hash the name in place of those, but with a handful of names, the difference is too small to measure. And there's no way to remove a token, as nothing removes a label or a type from a graph yet. In CMake lists dot text, the library gets the new source file, and the test program gets the new test, so ctest runs it with the others. The library is what sg and the tests link against, so both of them get the store. The store's tests go in a file of their own, token store test, next to the record file's. It includes the token store's header first, then cstdio, for remove, which deletes the file an earlier run left, and GoogleTest. Gives each name one token opens a temporary store of labels. Species gets token zero, Genus gets one, and adding Species again gives zero back. Find gives Genus's token, and nothing for Family, which nobody has added. Name gives Genus back for token one, and an empty name for k no token. Keeps its names in a file adds two types, EATS and LIVES IN, to a store in a file, closes it, and opens it again. LIVES IN still has token one, and token zero is still EATS, so the tokens in a graph's records keep their names once the graph opens again.
A chain in
10:33 In the graph's header file, we include the token store, for the token ID and the store's class. The node record's comment says what it holds now: its name, its label's token, the first of the relationships that start at it, the first of those that end at it, and the first of its properties. The name grows from forty-four bytes to forty-eight, the label becomes a token ID, and first in goes after first out. The relationship record's comment says it holds its type's token, and two links, the next relationship that starts at from and the next that ends at to. So a relationship is in a chain of each of its nodes, a chain out of the one and a chain into the other. Its type becomes a token ID too, and next in goes after next out, so the record holds six numbers of four bytes each. The static asserts check that a node is still sixty-four bytes, and a relationship twenty-four now. A page holds a hundred and seventy relationships, with sixteen bytes left at its end, as twenty-four doesn't divide four thousand and ninety-six. We could pad each record to thirty-two bytes, but that would waste eight bytes in each of them, where this wastes sixteen in a page. Direction is an enum class, with out and in, and its comment says what it picks: which of a node's relationships to follow, those that start at it, or those that end at it. The graph's comment adds a store each for the tokens of labels and types. K max label and k max type are the token store's k max name, so a label or a type can be up to thirty-one bytes long, and the facts we load are checked against them, as before. Flush writes the two stores' changed pages to their files too. Neighbours gets a direction, out by default, so the callers from earlier episodes go on walking out, and with in, it follows the relationships that end at the node. Label reads the node's token and asks the store for its name, and type does that for a relationship, for the page, which shows a relationship's type. The page counts add the two stores, and the private part gets them, labels and types. In graph, the constructor opens a temporary file for each store, and Open opens the folder's labels and types files, so a folder holds six files now. Add node starts a node with no token for its label, and with no relationship in, as well as none out. Add relationship is where the second chain comes in, and the new relationship's id is the record file's count, as Append is going to put it after the last one. Its type goes through the store, so a type gets its token here, the first time it's used. Then the start is read, and the comment over it says where the relationship goes: at the front of two chains, the out chain of the node it starts at, and the in chain of the node it ends at. So the relationship's next out is the start's first out, the relationship that was at the front of its chain until now. Then the start's first out becomes the new id, and the start's record is written back. The comment over the end says why it's read after the start is written: they're one node when a relationship goes from a node back to that node. Reading both first would lose the start's change when the end is written. Its next in is the end's first in, and the end's first in becomes the new id. Then the record is appended after the last one, and its id returned. So adding a relationship takes three writes now, where it took two, however long either chain is. Set label adds the label to its store, and keeps its token in the record. In Neighbours, which follows a node's relationships of one type, the type's token is looked up first, once for the whole walk. Find returns an optional, which is empty when the store doesn't have the type. Without a token for the type, no relationship has it, so there are none. Then out says which chain to follow, the first id comes from first out or first in, and each relationship's type is compared as a number, which is cheaper than comparing two strings. Going out, the neighbour is the node a relationship goes to, and going in, the node it comes from. Then the walk moves on to the next relationship out, or the next in. The name index keeps names as long as a node's, forty-seven bytes and a zero, so a page of the index holds seventy-eight of them, where it held eighty-five. In the API, the JSON for the page asks the graph for a node's label and a relationship's type, by name, as the records hold their tokens. The page goes on showing names, and doesn't need to know that tokens exist. In the graph's tests, follows relationships both ways adds the red fox, the tawny owl and the field mouse. The fox and the owl eat the field mouse, and the field mouse eats the wheat. What eats the field mouse is the fox and the owl, in the order they were added, along the chain of relationships that end at it, as the comment says. And what it eats is the wheat, along the chain of those that start at it. LIVES IN, a type no relationship has here, gives no neighbours going in, as the store has no token for it. The next test adds Ouroboros, the snake that eats its own tail, with a relationship from the node back to that node. That's the case the comment in Add relationship was about, as the start and the end are one record. Following it out and following it in both have to give Ouroboros back, which they wouldn't if Add relationship read the end before writing the start. Keeps its records in a folder gives the rabbit a label too. After the graph opens again, the clover's chain in has to lead back to the rabbit, and the rabbit's label has to come back from the store, by its token.
16:04 Let's build it, and run the tests, the old ones and the new. All forty-seven of them pass, and the walks from earlier episodes find what they found before, on records that hold tokens. We load the Wikidata graph, and the folder has two new files, labels and types. Each is two pages, a header and a page of names. The relationships file is about a quarter smaller than it was, at twenty-four bytes a relationship. With xxd, from the types file's second page, the first record is token zero, PARENT_TAXON, padded to thirty-two bytes, the single relationship type the Wikidata graph has. And from the relationships file's second page, relationship zero takes the order of frogmouths up to the birds, Aves. Its type is token zero, then come the frogmouths, node two, and Aves, node zero, and all ones for no next relationship out. Its next in is all ones too, as it was the first relationship to end at Aves. Relationship one starts halfway through the row above, and takes the potoos, node three, up to Aves, and in this row, its next in is zero. So Aves's chain in, of forty-five orders, ends with relationship one, and then relationship zero, the oldest.
Arrows on the left
17:18 Cypher writes a relationship that goes from the next node to the one before it with its arrow on the left, as in field mouse, then less than, minus, EATS in brackets, minus, then fox. In the parser's header file, the relationship pattern's comment says so: one written that way goes from the next node to this one. A relationship pattern gets a direction, from the graph's header file, which is out by default. Its comment says it's which way to follow the relationship from the node before it, out, or in when it's written with its arrow on the left. That way, the planner can hand the direction to Neighbours as it is. The comment on the query says that relationship i joins node i to node i plus one, as goes from isn't true of each of them any more. In the parser, parse query reads another relationship while the next token is a minus, or a less than, which is how a left arrow starts. The grammar over parse relationship gets a second line, for the arrow on the left, with no greater than at its end. Parse relationship reads a less than first, when there is one, and sets the direction to in. The lexer from episode seven reads less than and minus as two symbols already, so it needs no change. The type and its number of hops are read as before, between the colon and the closing bracket. After them come the closing bracket and a minus, as before, and when either is missing, it returns false. Then, with direction in, it's done, and otherwise a greater than has to follow, as an arrow on the left needs none on the right. A relationship written with an arrow at both ends fails then, at the greater than, as the node it expects isn't there. In the plan's header file, the comment on an expand adds that with direction in, its rows get the nodes that its relationships come from. A step gets a direction, out by default, which is which of its node's relationships an expand follows. In plan, the expand that plan query adds is written with designated initialisers, from C++ twenty, which name each field, as in dot kind and dot from. They have to come in the order the struct declares them, and the fields left out, the operator and the value, keep their defaults. So the step gets the relationship's direction, without writing out the fields between. In Run, an expand passes its direction on to Neighbours. In Explain, the expand's case gets braces, for a variable of its own. Out says which way the arrow goes, and the comment says so: its arrow points the way the relationships go. Going out, it's a minus and a bracket, and a bracket and an arrow on the right, as before. Going in, it's an arrow on the left, then a bracket, and a bracket and a minus. In the parser's tests, reads a relationship that points left parses who eats the field mouse, from the field mouse. Its single relationship is EATS, with direction in, and the node after it is a, the one it comes from. Says what it expected gets a relationship with an arrow at both ends, which fails at the greater than, nineteen characters in, where an opening bracket should be. In the plan's tests, expands the way the arrow points plans that query: a seek for the field mouse, then an expand into a, with the arrow on the left. Then follows relationships backwards runs it on the animals, and the comment says what it asks: what eats the field mouse, and what eats what eats the wheat. The red fox and the tawny owl eat the field mouse. And two hops left from the wheat come to the field mouse, and then to the fox and the owl, which eat it.
20:53 Let's build it, with arrows on the left in the parser, and run the tests, the three new ones among them. All fifty of them pass, the old walks and the new ones. With the Wikidata graph loaded, let's ask for the genera of Manidae, starting from the family, and following PARENT_TAXON in. There are four of them, the three genera of living pangolins, and Manus, which Wikidata lists with a single species. It reads a dozen pages, as the plan finds the family in the index, and follows its chain in. But written the other way round, with the family on the right, the question about its species still starts with a label scan of the species, as our planner starts from a pattern's first node, whatever it is.
Where a plan starts
21:36 Real planners pick where to start from what each start costs. Neo4j and Kùzu estimate it from statistics they keep on the graph, such as how many nodes have each label. Ours is going to follow a simpler rule, in the spirit of last episode's. A node with a name is the cheapest to find, as the index goes straight to it, then a node with a label, and then any node. So for the pangolins, the plan starts with a seek for Manidae, and its filter on the label, Family. Then it expands to the left end of the pattern, following PARENT_TAXON in, twice, as the pattern asks for two hops. The species' filters come once they have a slot, and their names are returned. The pattern's relationships point right, from the species to the family, so going from the family to the species, each one is followed the other way, in.
22:28 In the plan's header file, plan query's comment says it starts from the node of its pattern that's cheapest to find. In plan, cost to find says how costly a node is to find, when the plan starts from it. The order has its reasons: a name is found in the index, a label by a scan that keeps fewer rows, and otherwise each node in the graph is a start. So it returns zero for a node with a name, one for a node with a label, and two for any other. A label scan reads each node's record, as a scan of all the nodes does, and what it saves is the rows it drops, which aren't expanded. Reversed turns out into in, and in into out, for a relationship followed from its other end. Add expands takes the expands out of plan query, as it's going to need them twice, once for each end of the pattern. It's given the query, the relationship, the direction to follow it in, the node it leads to, and the slot it starts from. For each hop, the comment from plan query comes along: each hop is an expand into a slot of its own, the last of them the pattern's node, and the ones before it nodes it doesn't name. So a new slot gets the node's variable on the last hop, and none before it. To is the new slot's index, and an expand goes from the slot to it, with the relationship's type and the direction it's given. Slot moves on to the new one, and once the hops are done, the node's filters come in, on its slot, and the slot is returned. Over Add expands, the comment says it adds the expands from the node in the slot to the pattern's node, along the relationship, then the filters on the node, and returns the slot it ends up in. In plan query, the comment over the start says what's new: the plan starts from the node of the pattern that's cheapest to find, the first of them when there's a tie. First is the index of that node, which a loop finds, keeping the first node with the lowest cost, and the start is that node, in place of node zero. The seek, the label scan or the scan of all the nodes come next, as before, with the start's filters. Then the old loop goes, and the expands it held have moved to Add expands. It went through the relationships from the first one, expanding each of them to the right, which was all a plan could do when it started from node zero. Two loops take its place, one for each end of the pattern. Each of them keeps track of the slot it's at, as Add expands returns it, so the next relationship starts from the node the last one reached. The comment over them says the plan expands to the pattern's right end, then to its left end, following each relationship there from the node after it, so the other way. Slot starts at zero, which is the slot the start went into. To the right, from the start's index up to the last relationship, each one is followed in the direction its pattern gives, to the node after it. Then slot goes back to zero, the start, and to the left, from the start's index down to one, relationship i minus one leads to node i minus one, and Reversed flips its direction. A pattern that starts at its first node goes to the right and no further, and plans as it did before. In the plan's tests, the scan test for the meadow becomes starts from the node that's cheapest to find, as it seeks the meadow now, and expands into its LIVES IN chain. The query is mvGPT's question about the pangolins, with endangered as the status, the species on the left, two hops of PARENT_TAXON, and the family on the right. The plan is the one we drew, from the seek, through two expands to the left, with a slot for the genus that has no variable, as the pattern doesn't name it, and then the species' filters. Its seek is on f, the family, with the filter on its label right after it, and the expands are written with their arrows on the left. And the comment over it says why: the family has a name, so the plan finds it in the index, and walks down to its species, in place of scanning each species. Starts in the middle runs a query on the animals, which asks who eats the field mouse, and what the field mouse eats. The name is in the middle of the pattern, so neither end is where the plan starts. The rows have the eater in a's column and the food in w's, whichever order the plan found them in. The plan finds the field mouse, goes right to what it eats, then left to what eats it. That's the wheat for each, and the fox and the owl.
26:39 With the planner built, and the Wikidata graph loaded, let's run the tests. All fifty-one of them pass, the planner's new test among them. Then mvGPT's question about the pangolins again, with EXPLAIN, and its plan starts from a seek for Manidae now, and walks its chain in. Running it, the three pangolins come back after thirty-three pages, where they took more than thirteen hundred, in a few hundredths of a millisecond. That's about forty times fewer pages, and about forty-five times less time.
Both chains in the UI
27:11 In the API's header file, Node JSON answers with a node's chains out and in now, newest first, each with the node at its other end, as its comment says. In the API, Chain JSON writes a chain of relationships as JSON, and the two chains share it. It's given the graph, the first id of a chain, and the direction to follow it in. Out says which way it's going, as in Neighbours, and the JSON it writes is a list, in square brackets. From the first id, it reads each relationship, and the node at its other end is the one it goes to, going out, and the one it comes from, going in. It writes the relationship's id, with a comma before each but the first, then its type, by name, and its properties, as an object. Then come the other node's id, its name and its label, so the page can draw it without asking for it, and where the record is kept, its page and its offset. Then the next id is the next out or the next in. The comment over it says what it writes: a chain from its first relationship to its last, which is the order they're kept in, newest first. Each has its type, its properties, the node at its other end and where it's kept, and the chain out goes on to each relationship's next out, and the chain in to its next in. In Node JSON, the loop that wrote the chain out goes, and the JSON gets outgoing, from the node's first out, and incoming, from its first in, both through Chain JSON. Then the node's chain of properties follows, as it did before. In index dot html, the button's label is draw its neighbours, as it's going to draw them both ways, and the relationships get two lists, out and in, each with a heading. In app dot js, the comment over expand says that double-clicking a node, or the inspector's button, draws the nodes at the other end of its relationships, those out of it and those into it. Expand takes outgoing and incoming from the record, the two chains. The nodes it draws are the other ends of both. A relationship out is drawn from the node to its other end, and one in from its other end to the node, so the arrows on the canvas point the way the relationships go. In inspect, the comment adds the chains out and in, and a loop fills both lists, each a pair of a chain's name and its arrow, so the two lists share their code. Each list gets a line for each relationship in its chain, newest first, as the server sends them. Each line has the type, an arrow pointing right for out and left for in, and the other node's name, with where the record is kept under it.
29:41 Back in the browser, the page at the end of this step opens on the dog family, as before, which the plan finds from Canidae now. Let's search for the cat family, Felidae, and pick it, which draws the family and opens its record. Its chain out has a single relationship, to its order, Carnivora. Its chain in has the fourteen genera of cats, from Lynx and the cheetah's genus down, newest first. And Expand draws its neighbours, which are the order above it, and the genera below it, with their arrows pointing at the family.
A fair benchmark
30:14 In episode seven, we said we'd make our benchmark against Neo4j and Kùzu fair, and it's time. Since episode three, sg bench has timed a walk, which goes straight to the graph, while Neo4j and Kùzu were each given a query in Cypher, with the name as a parameter. Kùzu plans it on each call, and Neo4j plans it once, and takes the plan from its query cache after that. So sg bench is going to time Cypher too, parsing and planning each query as well as running it. And now that our relationships go both ways, each database answers two questions from a thousand people: how many people are two hops of KNOWS away, following relationships out of the person, and following them in.
30:55 In main, we include Abseil's str cat, and str replace, for putting a name into a query. The usage line says sg bench takes a query with dollar name in it now, in place of a type and a number of hops. Count rows is new, and it's what the benchmark times for each start. It takes the graph and the query's text, and returns a status or, which holds either a number or an error. It parses the query, as sg query does, and returns the parser's error when the text isn't a query our subset has. Then it plans it, returning the planner's error when there is one, and otherwise it runs the plan, and returns how many rows came back. Its comment sums that up in a single line, over the function. It's called twice for each start, once to warm up, and once on the clock, so a start whose query fails is caught before any timing. Bench takes the query's text in place of a type and a number of hops. Its comment says what it does now: it times a query in our subset of Cypher, from each node named in the file, after a first pass that warms the system's caches, and prints the times as JSON. Our Cypher has no parameters, so each name goes into the query in place of dollar name, in quotes, and each query is parsed and planned, as well as run. Bench reads the names into a list of queries, each made with str replace all, which swaps dollar name for the name in single quotes. The first pass warms the caches, as before, and checks that each query can be answered, too, so a mistake in the query stops the benchmark with its error. The total of the rows starts at zero, and the list of times and the count of pages read before it are as they were. Then the timed pass parses, plans and runs each query again, between the two readings of the clock. In place of a walk from a node, the clock covers the lexer, the parser and the planner now, as it would for a query from a client. Each query's text was made before the clock started, so putting the name in isn't timed. It counts the rows with value or, which gives zero for an error, as there can't be one by then, and adds them up as the results. Main takes four arguments for bench now, and passes the query on. In make friends, each person gets a line of their own first, with the label Person, which they have in Neo4j and Kùzu too, as the comment says. Kùzu keeps people in a table named Person, and Neo4j's import gives them the label, so the three databases can match one pattern. Then the benchmark script, which is where the questions are asked. The docstring at its top says what it does now. It loads the friends graph into each database, as before, and then asks each of them two questions, from each person in the starts file, three times over. The questions are written in Cypher for all three, and it writes the medians. The questions are how many people are two hops of KNOWS away, following them out of the person, and into them. RUNS stays at three runs for each database. The old question, CYPHER, goes, as there are two of them now, and a part of each that differs between the databases. Questions holds the two patterns, out and in, which are one pattern written with the start's name at either end. Our Cypher has no count yet, so smollerGraph returns each of the people once, with RETURN DISTINCT, and the rows are counted. Neo4j and Kùzu return a count, so each pattern is followed by COUNT for them, and by ROWS for us. In the smollerGraph function, the load is timed as before, from outside sg, with the folder removed first. Then measured becomes a dictionary, with an entry for each question. For each of them, it runs sg bench with the question's pattern and ROWS, reads the JSON it prints, and keeps the results, the median and the ninety-fifth percentile, which is what the other two report. The time it took to open the graph, and the number of queries, which sg bench prints too, are left out. The ninety-fifth percentile is the time that ninety-five in a hundred queries stay under, which shows the slow ones that a median hides. In Kùzu's function, each question gets a timing of its own, through the connection's execute, with the question's pattern and COUNT, and the name as a parameter, as before. Neo4j's function does that through a session of its driver, over Neo4j's network protocol. In main, each database's results start with the median of its three loads, as r, which is what the line it prints is going to read from. Then, for each question, it checks that the three runs gave one answer. When a database answered differently from run to run, the comparison stops there, and says which database it was. Otherwise, it keeps the median of each measure across the runs, under the question's name. So a database's results end up with its load, then out and in, each with its results, its median and its ninety-fifth percentile. It prints a line for each database, with its load and the median of each question, in microseconds, padded so the three lines make columns. Then it checks that the three databases agree on both questions, and prints how many people they found, from smollerGraph's results, as all three are equal by then, before it writes the results.
Two hops in
36:09 Before we measure the three of them, here's what the second question used to cost us. On last episode's code, with the friends graph from episode three loaded, a hundred thousand people and a million relationships, let's ask who's two hops of KNOWS into the first of our thousand people. The plan has to scan each person, and walk two hops out of each, to find the ones that reach them. It takes about a second, and reads over nine thousand pages, to find seventy-eight people.
36:38 Now let's run the comparison on this episode's code, with nothing else busy on the machine. It loads the friends into each database, asks both questions from a thousand people, three times over, and runs Neo4j in Docker, so it takes a couple of minutes. SmollerGraph answers each question in tens of microseconds, with parsing and planning, about twenty-eight going out and thirty-seven going in. Kùzu takes over a millisecond for each, and Neo4j a little under a millisecond going out, and less going in. And the three agree on both answers, about a hundred thousand people each way, counting each person once for each start.
37:18 Here are the medians of the two questions side by side. Going out, smollerGraph is still a lot quicker than the other two, with the parser and the planner in the timing. It's about twenty-eight microseconds, where the walk took about six in episode five, so parsing, planning, checking labels and keeping distinct names cost us most of the time. Going in, it's about thirty-seven microseconds, where a scan took about a second. Neo4j's times still include a trip over its network protocol to a container, and Kùzu's a call from Python, while ours are measured inside sg, so we're not claiming to be faster than either. Both questions now cost us a similar amount, whichever end of the pattern has the name.
What's missing
38:00 Relationships both ways leave a few things out, and some of them are worth knowing about. A node's chain holds each of its relationships of one direction, whatever their type, so a walk along one type steps over the others, which Neo4j avoids with its groups by type. A query whose pattern has no name still scans, where an index on a label or a property would go straight to the nodes. Our planner picks its start by a rule, where Neo4j and Kùzu estimate how many rows each start gives, from statistics on the graph. And the graph is still written by sg load, all at once, while a graph that's written to needs to survive a crash part way through a write, which is what a write-ahead log is for.
Wrap-up
38:40 So, today smollerGraph learned to follow relationships both ways. Labels and relationship types became tokens, kept once each in a store of their own, which made room in the records. Each relationship is in two chains now, one out of the node it starts at and one into the node it ends at. Cypher reads relationships that point left, and the planner starts from the node it can find most quickly, and expands both ways from it. The page shows both chains, and expands a node both ways. And measured in Cypher against Neo4j and Kùzu, a question from either end of the pattern costs us tens of microseconds.
39:18 This is going to be an evolving project, so I'd love to hear from you. Let me know in the comments which questions you'd ask the animals from the other end, and if you'd like to follow along, subscribe to the channel. I hope you find this useful, and thanks for watching.