(smollerGraph)
  • Episode 14
  • 22 min

FastRP node embeddings in a graph database

Node embeddings in smollerGraph with FastRP, as Neo4j's Graph Data Science library computes them, the most similar nodes by cosine, embeddings kept on disk, and a page that draws a node's nearest.

1 November 2026 · Watch on YouTube

We give each node of smollerGraph a vector of numbers that stands for where it is in the graph, with FastRP, the way Neo4j's Graph Data Science library does it: a sparse random vector for each node, then rounds in which each node's vector becomes the sum of its neighbours'. Two nodes with similar neighbourhoods get vectors that point the same way, which a cosine measures, so we can ask which species are most like the lion, from the graph alone. The embeddings go into a file of their own, and the page draws the nodes most like a node, the less alike further away. It's a vanilla version of what GDS offers, written to see how it works.

Topics: Machine learning on graphs, Visualization

The code

Each step on screen is a tag in the database's repository. The code at the end of the episode is ep014/end.

  1. 4:13ep014/step-1FastRPBrowseChanges
  2. 11:48ep014/step-2On diskBrowseChanges
  3. 16:42ep014/step-3Similar nodes on the pageBrowseChanges

Transcript

Intro

0:00 Hello, and welcome to episode fourteen, where we're going to give each node of smollerGraph a vector of numbers that stands for where it is in the graph, and use those vectors to find the nodes most like each other. Here's where we'll be by the end of the episode.

0:16 By the end, the page can draw the nodes most like a node, from the shape of the graph alone. Here's the blue whale, and the ten nodes most like it, its own genus close by, and further out, the rorqual family and the humpback whale's genus, each line longer as the two are less alike.

0:33 The series' website has more about the project, and what it's building towards. The code is open source on GitHub, with a tag for each step of each episode, so that you can follow along. And each episode gets a page of its own, with its chapters and its code.

Last time

0:48 Last time, we found cheapest paths, in a graph whose relationships have a cost. Each friendship got a weight, as LDBC's benchmark weighs them, and Dijkstra's algorithm settled the cheapest node left each round, from a priority queue. From both ends, the search stopped once the two sides' next costs added up to the cheapest way found. And Cypher took Kùzu's W SHORTEST, while the page drew each weight. Paths answer questions about two nodes, and today we're going to look at each node on its own, and what its place in the graph says about it.

Today

1:23 Today has four parts, from the vectors up to the page. We're going to write FastRP, which gives each node a vector of numbers, as Neo4j's Graph Data Science library computes it. With those vectors, sg similar finds the nodes most like a node, and the vectors go into a file of their own, so they're computed once. Then the page draws a node's nearest, with the cosines on the lines. So, let's start with why a vector for a node is worth having.

Why embeddings

1:52 An embedding turns a node's place in the graph into a list of numbers, a vector, so that nodes with similar neighbourhoods get vectors that point in similar directions. With them, finding the nodes most like a node is a comparison of vectors, which needs no pattern to describe what alike means. A shop's graph of customers and products can recommend products bought by people whose vectors are close to yours, and a bank can look for accounts placed in the graph like known fraud. And machine learning models take lists of numbers, not graphs, so embeddings are how a graph's shape becomes something a model can learn from. For our animals, a species' vector is going to say where it sits in the tree of taxa, so species that share a genus or a family end up alike.

Neo4j's GDS

2:38 Neo4j does this in its Graph Data Science library, which runs graph algorithms on a copy of the graph that it projects into memory. It has several ways to embed nodes, which work quite differently. FastRP, short for fast random projection, mixes random vectors along the relationships, and needs no training. Node two vec learns vectors from random walks, and GraphSAGE trains a small neural network, which is where we're heading next time. The embeddings can be written back to the graph, as a property of each node. Then its k nearest neighbours algorithm, or a vector index in the database, finds the nodes most like each other. We're going to write FastRP, as it's the simplest, and a vanilla version of it, to see how it works.

FastRP

3:22 FastRP starts from a random vector for each node, of a few hundred numbers. Most of the numbers are zero, and the rest are one or minus one. In that many dimensions, two random vectors like these are close to right angles from each other, so each node starts out unlike each other node. Then come the rounds, and in each, a node's new vector is the sum of its neighbours' vectors from the round before. So after one round, a species' vector is its genus's random one, and after more, it carries the family and the order too. Each sum is scaled to a length of one, so a node with many neighbours doesn't get a longer vector. The embedding adds up the rounds, so it holds both the near neighbourhood and the far one. Two nodes whose neighbourhoods overlap end up with vectors that point in nearly one direction, and the cosine of the angle between them says how alike they are.

4:13 The embeddings get a header file of their own, embed. We include array, for a vector of a fixed size, cstddef and cstdint for sizes and numbers, string view, utility, for pairs, and vector, then the graph's header. K embedding size is how many numbers an embedding has: two hundred and fifty-six. GDS's FastRP lets you choose it, and more numbers keep random vectors further from each other. Embedding is an std array of that many floats, and its comment says it stands for where the node is in the graph, so that nodes with similar neighbourhoods get vectors that point in similar directions. FastRP takes the graph, the relationship type to follow, and a seed for the random numbers, and returns an embedding for each node. Its comment walks through the algorithm: a sparse random vector for each node, then five rounds. In each round, a node's vector is the sum of its neighbours' vectors from the round before, followed both ways, and scaled to a length of one. The embedding adds up the rounds from the second on, and a seed gives back its vectors each time. Cosine compares two embeddings, and its comment says it's 1 when they point one way, 0 at right angles, and minus one when they're opposite. Most similar returns the k nodes whose embeddings are most like a node's, with their cosines, by comparing it with each of the others, as its comment says. In embed, we include algorithm, for partial sort, cmath, for the square root, and random, for the Mersenne twister, the standard library's generator of random numbers. In an unnamed namespace, Normalise is a helper, and its comment says it scales a vector to a length of one, unless it's all zeros. It adds up the squares of the vector's numbers, and when that sum isn't zero, it divides each number by its square root, which is the vector's length, so the new squares add up to one. FastRP's signature takes the graph, the type and the seed, over two lines, and count is the number of nodes. The generator gets its seed, and each node's first vector is filled with draws from it. The comment over the generator explains the draws: each number is 1 or minus one, with a chance of one in six each, and otherwise zero. That's a very sparse random projection, which keeps the vectors of unrelated nodes close to right angles from each other. A draw from zero to five does that: zero gives 1, one gives minus one, and the other four give zero. Neighbours holds a list for each node, and its comment says why: each round goes through each node's neighbours, so they're read from disk once, for all five. For each node, Neighbours reads them both ways. Then come the weights of the rounds, which are GDS's iteration weights. Its comment says why we use two rounds more than its default of three: in a tree of taxa, a species' relatives are four hops away, through the genus and the family. The first round's weight is zero, as GDS's is, since after one round, a species' vector is no more than its genus's random one. Then, for each round, next starts at zeros, and each node adds up its neighbours' vectors from the round before, number by number. Normalise scales the sum, and the round goes into the node's embedding, times its weight. Then the round becomes the one the next round reads. Cosine works out the dot product and the two sums of squares in one pass. It divides the dot product by the square root of the sums multiplied, or gives zero for a vector of zeros. Most similar keeps a vector of pairs, each a node and its cosine. It goes through each of the other nodes, skipping the one it was given, and keeps each cosine, with its node. K is at most the number of pairs. The k largest cosines go to the front, in order, and the rest stay unsorted behind them, with partial sort, as a full sort isn't needed for the first k. Then the vector is cut down to k, and goes back, the most similar first. The CMake file gets embed, in the library, and its tests, in the test program. Embed's tests go in a file of their own. We include sstream, for facts written in a string, string view, utility and vector, then facts, the graph's header and GoogleTest. The test fixture's set up loads a small piece of the tree of taxa. The lion and the tiger are in Panthera, the grey wolf and the golden jackal in Canis, and Panthera and Canis are both in Carnivora. The comment over them calls them two genera of the order of carnivores, with two species each. Once they're loaded, the fixture computes their embeddings, with a seed of forty-two, and keeps them. Of is a helper that gives a node's embedding by its name, and the fixture keeps its graph and its embeddings as members. The first test is about nodes that share their neighbours. The lion and the tiger have a cosine of one, as their neighbourhood is Panthera, and nothing else. The comment over the check says so, and that the wolf's is further away, which the next check makes sure of. Then it computes the embeddings again, and checks that the seed gives back its vectors. Finds the most similar nodes asks for the two nodes most like the lion. There are two of them, the first is the tiger, and the cosines come in order, the larger first.

9:20 In main, we include embed's header, and the usage gets a line for sg similar, which takes a graph, a node's name, a relationship type and k, the number of nodes to print. Similar finds the node by its name, and says so when there's none. Then it reads k, which has to be a whole number of one or more. It times FastRP, with a seed of forty-two, and prints how many embeddings it computed and how long they took. Then, for each of the k most similar nodes, it prints the cosine, to three decimal places, the node's name, and its label in brackets. Its comment says it prints the k nodes most like the named one, as their embeddings say, computed with FastRP along relationships of the type. In main, similar is a command with the graph, the name, the type and k, and the check for a command it knows gets it too. When the command is similar, main returns what Similar returns.

10:16 Let's build it, with FastRP and sg similar, and run the tests. All sixty-four of them pass, the two new ones among them. With the Wikidata graph loaded, let's ask for the twelve nodes most like the lion. The embeddings of all twenty-two thousand nodes take a few dozen milliseconds. At the top, with a cosine of one, are the tiger, the leopard, the jaguar and the snow leopard, the other species of Panthera. They have the lion's neighbourhood, a single relationship to the genus, so their vectors are the lion's. Then comes Panthera, then the cat family, Felidae, and other genera and species of cats, the serval and the cheetah's genus among them, at about a half. Two random vectors of two hundred and fifty-six numbers have a cosine of about zero, so a half is a lot, and the order of the list follows the tree of taxa, from nothing more than the relationships.

On disk

11:08 Our sg similar computes each embedding each time it runs, which is quick on twenty-two thousand nodes, and wasted work even so, as the vectors don't change until the graph does. So sg embed is going to compute them once, and keep them in a file of records of their own, an embedding for each node. Two hundred and fifty-six floats of four bytes are a kibibyte, so four of them fit in a page, and a node's id says where its embedding is, as it does for its record. GDS, for its part, can write each embedding back as a property of its node. Our properties hold a number or a string, so a file of their own suits ours better. Then sg similar reads them back, and doesn't compute them.

11:49 The graph's records are going to hold embeddings, so k embedding size and the embedding move out of embed's header file, along with the include of array. In the graph's header file, they come in before the property's value, with array included. K embedding size comes first, with its comment, and then the embedding, an std array of floats. The comment over the embedding keeps its words: a vector of numbers that stands for where the node is in the graph, so that nodes with similar neighbourhoods get vectors that point in similar directions. Then it adds that on disk, it's a record of its own, a kibibyte, whose number is the node's id, so four fit in a page. A static assert checks that size, as the record file copies records as bytes. Flush writes the embeddings' changed pages too, with the other files'. Set embedding keeps a node's embedding, in place of the one it had, and its comment says the nodes are given theirs in the order of their ids. Embeddings returns the embeddings of all the nodes, in the order of their ids, or none, unless there's one for each, as a vector of all of them is what Most similar takes. The page counts add the embeddings file's reads, in front of the other files' reads. In the sum of the pages written, it goes in front again of the other files' writes, and in the private part, the graph gets a record file of embeddings. In graph, the constructor opens a temporary file for them, and Open opens the folder's file of embeddings, after the types. Set embedding writes over a node's record when it has one, and otherwise appends it, which is why the nodes come in order: node seven's embedding is appended as the eighth record. Embeddings checks that there's one for each node, and returns none when there isn't, so a graph that has gained nodes since doesn't hand out a short list. Otherwise it reserves room for all of them, and reads each record, through the buffer pool. In main, the usage gets a line for sg embed, which takes a graph and a relationship type, and sg similar no longer takes a type, as the embeddings are computed before it runs. Embed is the function behind sg embed, and its comment says what it does: it gives each node an embedding with FastRP, along relationships of the type, and keeps them in the graph's folder, so sg similar can read them. It reads the clock, and computes the embeddings with FastRP, with the seed of forty-two, as before. A loop sets each node's embedding, in the order of their ids, and then it flushes the graph, so they're written to disk before the clock stops. It prints how many embeddings there are, of how many numbers, and how long they took, in seconds, then the pages read and written, the writes being mostly the embeddings'. The comment over Similar changes to say it prints the k nodes whose embeddings are most like the named node's, by their cosines. Its signature loses the type, and in place of computing the embeddings, it reads them from the graph. When there are none, it prints an error, which says that sg embed keeps them, and returns one, so a script can tell. The cosine's line sets its fixed decimal places, now that nothing printed before it does, and goes on to the node's name. In main, embed is a command with a graph and a type, and similar takes a graph, a name and k. The check for a command it knows gets embed, and when the command is embed, main returns what Embed returns. In embed's tests, we include stdlib, for mkdtemp, which makes a folder with a name of its own, and string, for the folder's path. Keeps embeddings in the graph's folder makes a new folder in the test's temporary directory, so nothing is left in it from an earlier run. In a block of its own, so the graph closes at its end, it opens a graph in that folder, and adds the lion, with its relationship to Panthera. Before any embeddings are kept, the graph has none to give, which the comment over that check says too. Then it computes the embeddings with FastRP, and sets each node's, one by one, in the order of their ids. Once the graph has closed, a second graph opens the folder, and its embeddings, read back from the file, are the ones FastRP computes for it.

15:54 With the Wikidata graph loaded, let's run the tests. All sixty-five of them pass, with the test that keeps embeddings in a folder. sg embed computes the embeddings of the twenty-two thousand nodes, in about a tenth of a second, and writes about fifty-five hundred pages. In the folder, the embeddings file is twenty-two megabytes, nearly three times the rest of the graph together. A kibibyte for each node is a lot next to a node's record of sixty-four bytes, so the size of a vector is a trade between how far apart random vectors stay, and the room they take. Then sg similar reads them, for the ten nodes most like the blue whale. Its genus comes first, the other rorquals and Balaenoptera, then the rorqual family, Balaenopteridae, and Megaptera, the humpback whale's genus.

Similar nodes on the page

16:42 In the API's header file, k similar is how many of the most similar nodes the page draws, ten, as its comment says. Similar JSON takes the graph and a node's id, and its comment says it returns the k similar nodes most like the node, the most alike first, each with its name, its label and its cosine. An id the graph doesn't have is an error, and so is a graph without embeddings. In the API, we include cmath, for rounding, and embed's header. Similar JSON reads the id as a number, and when it isn't one, or the graph has no node with it, it answers not found. It reads the embeddings, and when there are none, the error says that sg embed keeps them. Then it starts a list, as the value of the key similar. For each of the most similar nodes, it appends an object, with its id, its name, its label, and its cosine, rounded by multiplying it by a thousand, rounding, and dividing again. The comment over that says three decimal places are plenty to tell the nodes apart. In the server, the path api slash similar, then a node's id, gets a handler, as api slash node does for a node's record, and it sends what Similar JSON answers. In the API's tests, we include vector, and embed's header, for FastRP. Answers with the most similar nodes builds a graph of three nodes: Panthera, and the lion and the tiger, each with a relationship to the genus. Then it asks for the nodes most like the lion, which is node one. With no embeddings kept yet, the answer is a failed precondition, and the comment over the check says why: without embeddings, there's nothing to compare. So the test computes them with FastRP, and sets each node's, in the order of their ids. Then it asks again, and the comment over that call says what to expect: the lion and the tiger share their neighbour, so they're alike. The answer is ok, and it starts with the tiger, node two, with a cosine of one. And node three, past the last node, is not found. On the page, the inspector gets a second button, Similar: draw the nodes most like it, which takes the first button's margin. In app, clicking the inspector's second button calls Similar, with the node the inspector shows. The comment over that says the second button draws the nodes whose embeddings are most like the node's, joined to it by their cosines, when sg embed has kept them. Similar is an async function, which fetches api slash similar for the node, and waits for its answer. When the answer is an error, the status line shows it, in the error's colour, and it stops there. Otherwise, the lines start as an empty list, and the comment over it says there's a line from the node to each of them, with its cosine, and the less alike, the longer the line. For each similar node, a line goes from the node to it, with the type SIMILAR, which no relationship in the graph has. The cosine is its property, to two decimal places, so the page writes it on the line. Each line's distance is eighty, plus three hundred times one minus the cosine, so a cosine of one is eighty pixels away. Then the view shows the node and its similar nodes, with those lines, the legend follows, and the status line says what's drawn. In the view, the layout's links take their distance from the line, when it has one, and fifty otherwise, as before, and the comment over the layout says so. And in the Compose file, the database's container runs sg embed on the Wikidata graph after it loads it, and before it serves it, so the page's server has embeddings to read.

20:13 In the browser, with the containers from this step running, the page opens on the dog family, as before. Let's look for the lion, and pick it, which opens its record in the inspector. Then the new button draws the nodes most like it. The other species of Panthera sit close, at one, with the genus, and the cats of other genera further out, around a half, the serval and its genus, the jaguarundi's and Pallas's cat's, with the cat family among them. The status line says these are the ten nodes most like the lion, by the cosines of their embeddings.

What's missing

20:48 Our embeddings leave a few things out, and they're worth knowing about. FastRP mixes vectors by a fixed rule, while GraphSAGE learns how to mix them, for a task, and it's a small neural network on the graph. GDS's FastRP can start from a node's properties as well as from random numbers, so a species' weight could count, where ours knows the shape of the graph and nothing else. Our most similar nodes come from comparing a node with each of the others, where a vector index, such as Neo4j's, finds close vectors without looking at each. And keep in mind that this is a vanilla version of what GDS offers. Theirs is built for graphs far bigger than ours, with years of engineering behind it, while ours is there to show how an embedding comes about.

Wrap-up

21:35 So, today smollerGraph learned to give each node an embedding. FastRP starts from a sparse random vector for each node, and in each round, a node's vector becomes the sum of its neighbours', so a node ends up carrying its neighbourhood. A cosine says how alike two nodes are, and the lion's nearest are the other big cats, then the rest of the cat family. The embeddings go into a file of their own, a kibibyte for each node, and the page draws a node's nearest, the less alike further away.

22:05 This is going to be an evolving project, so I'd love to hear from you. Let me know in the comments which species you'd like to see the nearest of, and if you'd like to follow along, subscribe to the channel. I hope you find this useful, and thanks for watching.