Introduction
Wikipedia Path turns French Wikipedia into a graph of links, then finds the shortest chain of clicks from one article to another.
Every article is a node. Every link from one article to another is an edge. With this graph, you can answer questions like “how many clicks from Tour Eiffel to Pikachu?”:
$ WikipediaPath.GraphBuilder path "Tour Eiffel" "Pikachu"
Searched 99,483 pages in 30 ms.
2 clicks from 'Tour Eiffel' to 'Pikachu':
0. Tour Eiffel
1. Jeu vidéo
2. Pikachu
What is in the repository
| Path | Content |
|---|---|
WikipediaPath.GraphBuilder/ | Command-line tool: downloads the dumps, builds the graph, reads it |
WikipediaPath.GraphBuilder.Tests/ | xUnit tests |
docs/ | This book, and the WGRF file format specification |
flake.nix | Nix dev shell, package and local MariaDB scripts |
How it works, in short
downloadfetches the SQL dumps of French Wikipedia and a list of date and country pages from Wikidata.decompressunpacks the.gzfiles.provisionloads the SQL dumps into a local MariaDB database.buildreads the database and writes one binary file,graph.wgrf.info,exploreandpathread that file.
The graph file uses the WGRF format. It is a compact, memory-mapped layout built for fast breadth-first search. The specification describes it byte by byte.
Size of the data
Numbers from the frwiki dump of 2026-09-01:
| Item | Size |
|---|---|
| Articles (nodes) | 2,777,420 |
| Links (edges) | 235,141,317 |
| Searchable names (titles and redirects) | 4,619,033 |
Compressed dumps (.gz) | about 2.7 GB |
| Decompressed SQL | about 12.5 GB |
| MariaDB data directory | about 64 GB |
graph.wgrf | about 1.1 GB |
Limitations
- Only French Wikipedia (
frwiki) is tested. The--wikioption exists, but the date and country examples in the spec are French. - The clickstream covers one month and the dumps another, so some measured links are missing from the graph and their clicks are dropped.
- Wikidata categories come from a live query, so they can be newer than the dump.
License
Wikipedia Path is licensed under the GNU Affero General Public License v3.0 only
(AGPL-3.0-only). See the LICENSE file at the root of the repository.
Local env
Requirements
- Linux, x86-64 or ARM64.
- Nix with flakes enabled. The dev shell brings everything else: the .NET 10
SDK, MariaDB, clang (for the native AOT build),
perf, the .NET profiling tools andmdbook. - About 80 GB of free disk for the dumps and the database (see Size of the data).
- About 8 GB of RAM for the MariaDB buffer pool. You can change this, see Local database.
Enter the dev shell
nix develop
The shell sets WPATH_DB_DIR to .mariadb/ at the root of the repository and MYSQL_UNIX_PORT to
the socket inside it. Every command that talks to MariaDB uses these values by default.
Build a graph from scratch
Run these commands from the root of the repository. By default, every file goes into dumps/.
db-start # start the local MariaDB
dotnet run --project WikipediaPath.GraphBuilder -- download
dotnet run --project WikipediaPath.GraphBuilder -- decompress
dotnet run --project WikipediaPath.GraphBuilder -- provision # takes hours
dotnet run --project WikipediaPath.GraphBuilder -- build
The result is dumps/graph.wgrf. The pipeline page explains each step.
You can also build the native binary once and call it directly:
nix build
./result/bin/WikipediaPath.GraphBuilder --help
Or run it without a checkout:
nix run . -- --help
Use the graph
dotnet run --project WikipediaPath.GraphBuilder -- info
dotnet run --project WikipediaPath.GraphBuilder -- path "Tour Eiffel" "Pikachu"
dotnet run --project WikipediaPath.GraphBuilder -- explore "Pikachu" --max-depth 1
These commands only need the .wgrf file. They don’t need MariaDB.
Read this book locally
mdbook serve docs --open
The build pipeline
Building a graph takes four commands. Each one reads the output of the one before.
dumps.wikimedia.org ──download──▶ dumps/*.gz ──decompress──▶ dumps/*.sql
Wikidata query service ──download──▶ dumps/frwiki-wikidata-categories.tsv
dumps/*.sql ──provision──▶ MariaDB tables
MariaDB tables + categories .tsv + clickstream .tsv ──build──▶ dumps/graph.wgrf
1. download
Fetches, from a Wikimedia dumps mirror:
| File | Used for |
|---|---|
frwiki-<date>-page.sql.gz | Titles, namespaces, which pages are redirects |
frwiki-<date>-redirect.sql.gz | Where each redirect points |
frwiki-<date>-linktarget.sql.gz | Link targets, by title |
frwiki-<date>-pagelinks.sql.gz | Links, from a page to a link target |
frwiki-<date>-page_props.sql.gz | The Wikidata item of each article |
clickstream-frwiki-<month>.tsv.gz | How often readers follow each link |
With --date latest (the default), it picks the newest dump run where all five tables are
finished.
It then asks the Wikidata Query Service which items are dates or countries, and writes
frwiki-wikidata-categories.tsv. See download.
2. decompress
Unpacks every .gz file in the directory, several files at once. See
decompress.
3. provision
Loads every .sql file into MariaDB with the mariadb client. Each table is dropped and created
again. This is the slow step: pagelinks alone is about 9 GB of SQL. See
provision.
4. build
Reads five tables from MariaDB, the categories file and the clickstream when there is one, then
writes graph.wgrf. The database is only read, never changed. See build.
Safe to stop and run again
Every step writes to a temporary name first (.part or .tmp) and renames the file only when it
is complete. A file under its final name is always complete.
downloadskips files that are already there with the right size, and resumes a.partfile with an HTTP range request.decompressskips files that are already decompressed.downloaddoes not query Wikidata again if the categories file exists. Delete it to refresh.
provision is the exception: it starts each table over.
Local database
The builder does not parse SQL dumps itself. It loads them into a local MariaDB server, then queries the tables. The dev shell provides the server and three scripts to manage it.
Scripts
| Script | What it does |
|---|---|
db-start | Creates the data directory on first run, starts the server, creates the wikipedia database |
db-stop | Stops the server |
db-reset | Stops the server, deletes all data, starts a fresh server |
Open a SQL shell with:
mariadb wikipedia
Where the data lives
- Data directory:
$WPATH_DB_DIR/data, which is.mariadb/datain the repository. - Socket:
$WPATH_DB_DIR/mariadb.sock. The server does not listen on TCP. - Log:
$WPATH_DB_DIR/mariadb.log.
.mariadb/ is in .gitignore.
Settings
The server is tuned for bulk loading of data you can download again. It gives up durability for
speed: no binary log, no doublewrite buffer, and the log is not flushed on each commit. If the
machine crashes during provision, run provision again.
| Variable | Default | Effect |
|---|---|---|
WPATH_DB_BUFFER_POOL | 8G | InnoDB buffer pool size |
WPATH_DB_NAME | wikipedia | Database created by db-start and used by provision and build |
Set them before db-start, for example WPATH_DB_BUFFER_POOL=16G db-start. The buffer pool size
applies each time the server starts.
Be careful with db-reset
db-reset deletes every loaded table. Loading them again with provision takes hours. Only run
it when you really want an empty database.
Read-only access from build
build never writes to the database. Each query runs in a session opened with
SET SESSION TRANSACTION READ ONLY, and the builder checks @@session.transaction_read_only
before it reads any row. If the check fails, the build stops.
From Wikipedia to a graph
This page explains, in plain words, how build turns Wikipedia tables into nodes and edges. The
exact rules are in the “Builder responsibilities” part of the
WGRF specification.
Nodes are articles
A node is a page of the main namespace (page_namespace = 0) that is not a redirect. Talk pages,
user pages, categories and templates are not in the graph.
Nodes are numbered from 0, in the order of their Wikipedia page_id. The graph keeps the
page_id of each node in the page_id column, so you can go back to Wikipedia.
Titles are stored as Wikipedia shows them, with spaces: Tour_Eiffel becomes Tour Eiffel.
Redirects are names, not nodes
A redirect such as Paris (France) is not a node. The builder follows it to the real article and:
- adds its title as an extra searchable name (an alias) for that article,
- rewrites every link to the redirect so that it points to the article.
The builder follows chains of redirects up to 8 steps. It drops a redirect that loops, is longer, points to a missing page, to another namespace or to another wiki. Links to a dropped redirect are dropped too.
Edges are links
The pagelinks table says “page A links to link target T”. The linktarget table gives the title
of T. The builder resolves that title to a node, through redirects if needed.
A link becomes an edge only when both ends are articles in the graph. Then, for each article:
- targets are sorted by node id,
- duplicates are removed (two links can reach one article through different redirects),
- a link from an article to itself is removed.
Red links (links to pages that don’t exist) are dropped.
Categories come from Wikidata
Some pages are hubs that connect almost everything: dates (14 juillet, 1913, XIXe siècle)
and countries (France). They make paths short but not interesting. To let you skip them, each
node has one category byte.
The category comes from the Wikidata item of the article:
downloadasks the Wikidata Query Service for all items that are an “instance of” a day, a date, a month, a year, a decade, a century, a millennium, a “year in topic” page or a country, and that have an article on French Wikipedia.buildreads thepage_propstable to find the Wikidata item of each article, and looks it up in that list.
The spec has the full list of values and the Wikidata classes behind each one.
path and explore use this column with --exclude-date-page and --exclude-country.
Clicks come from the clickstream
Wikimedia publishes a monthly
clickstream: how many times
readers went from one page to another. When build finds a clickstream file, it gives each edge
the number of clicks measured on it, in the click_count column.
- Only rows of type
linkcount. Rows from search engines, other sites or the search box don’t. - Both titles resolve like links do, through redirects. Clicks that land on the same edge through different redirects add up.
- A row whose link is not in the graph is dropped. The clickstream month and the dump date differ, so a link can have been added or removed in between.
- The clickstream leaves out pairs with fewer than 10 clicks in the month. Most edges have no count at all: that means “not measured”, not “never clicked”.
Each node also gets a view_count: the sum of every clickstream row that ends on the page,
whatever the referer (another article, a search engine, another site, none). It is close to the
page’s views for the month, a little lower because of the missing small pairs.
path and explore use both columns, see Path search. They count a missing
value as 0.
What the graph looks like
Output of info on the 2026-09-01 dump:
Degrees mean median p99 max zero
out-links 84.7 40 612 5,374 254 dead ends
in-links 84.7 14 862 570,854 46,002 orphans
reciprocal edges: 112,781,200 (48.0 %), linked both ways
- A typical article links to about 40 others.
- A few pages get a huge number of links:
Francehas more than 550,000 incoming links. - 46,002 articles have no incoming link: you can’t reach them by clicking.
- 254 articles have no outgoing link: a path can end there, but not go through them.
Path search
path finds a chain of links between two articles. --strategy picks what “best” means:
| Strategy | Finds | Search |
|---|---|---|
followed | The links readers click most (default) | Followed paths |
shortest | The fewest clicks, all links counting the same | Bidirectional BFS |
popular | A way through pages readers click into most | Page costs |
niche | A way through pages few others link to | Page costs |
niche-clicks | A way through pages readers rarely click into | Page costs |
niche-views | A way through pages readers rarely visit | Page costs |
followed, popular, niche-clicks and niche-views read the click_count and view_count
columns. A link or a page without a count counts 0. On a graph built without a clickstream,
every count is 0: followed then returns a path with the fewest clicks, and the command warns
you. strategies prints how each one scores a path.
Bidirectional breadth-first search
A plain breadth-first search (BFS) starts from the first page and visits its links, then the links of those links, and so on. With about 85 links per page, the number of pages grows very fast at each level.
path searches from both ends at once:
- The forward side starts at the source page and follows links forward.
- The backward side starts at the goal page and follows links backward: “which pages link to this one?”
At each step, the search grows one whole level of one side. It stops as soon as a page is reached by both sides. Because each side is complete up to its depth, that page closes a shortest path.
Each side keeps, for each page it reached, the page it came from. The path is rebuilt by walking these links back from the meeting page to both ends.
The backward side without a reverse index
A WGRF file stores only outgoing links. To find “pages that link to X”, you need a reverse index, and the format does not have one yet (see “Open / deferred” in the spec). Building one when the file loads takes several seconds.
Instead, a backward step scans every link in the graph once, in parallel, and keeps the links that point into the backward frontier. This costs the same whatever the frontier size: about 235 million links read in order.
A forward step reads only the links of the frontier pages, but in random order.
So the search picks the side to grow by cost:
- If the forward frontier has fewer than 5 links per node in the graph (about 14 million links for French Wikipedia), it takes a forward step.
- Otherwise, it takes a backward step with a full scan.
For example, Tour Eiffel to Pikachu visits about 100,000 pages and takes about 30 ms.
Parallel levels with stable results
explore and the forward steps of path expand a level in parallel. Several threads can reach
the same new page at the same time. To keep the result the same on every run, each new page keeps
the parent with the lowest position in the frontier, as a single-threaded search would. The
output does not depend on thread timing.
Followed paths
path --strategy followed looks for the path readers are most likely to click through, from the
clickstream.
Link cost
A link’s cost is about how unlikely its click is, in bits. It compares the link’s clicks with the clicks on all the links of its page:
cost = 1 + bits(clicks out of the page) - bits(clicks on the link)
| Share of the page’s clicks | Cost |
|---|---|
| more than half | 1 |
| about a quarter | 2 or 3 |
| about a thousandth | 11 |
| no clicks | 33 |
A link without clicks costs 33, more than any clicked link. So the search takes a long chain of clicked links before one unclicked link. The counts are shares of each page’s own clicks: a link that gets most of the clicks of a small page costs as little as the main link of a big one.
Dijkstra with buckets
The cost belongs to the link, so a page can be reached again later at a lower cost. The search is Dijkstra’s algorithm: it fixes a page’s distance only when it takes the page out of the queue. Costs are integers from 1 to 33, so the queue is one bucket per distance (Dial’s algorithm).
The search runs forward only, on one thread, and takes pages in the order they entered their bucket, so the result is the same on every run. The clicks out of each page come from one parallel scan when the command starts.
Page costs
popular, niche, niche-clicks and niche-views put the cost on the page you enter instead
of on the link. They differ by what they count for each page and whether a high count is cheap or
expensive.
| Strategy | Count | Cheap pages |
|---|---|---|
popular | clicks on links into the page | high counts |
niche | links into the page | low counts |
niche-clicks | clicks on links into the page | low counts |
niche-views | the page’s view_count | low counts |
The in-link and click counts come from one parallel scan of every link when the command starts, about 100 ms on French Wikipedia.
Niche: cost from rarity
The niche strategies make entering a page cost the number of bits of its count, at least 1:
| Count | Cost |
|---|---|
| 0 or 1 | 1 |
| 2 to 3 | 2 |
| 4 to 7 | 3 |
| 1,024 to 2,047 | 11 |
| about 100,000 | 17 |
Every page costs at least 1, so a path does not get long just to use small pages: three pages with 10 in-links (cost 4 each, 12 in total) lose to one page with 1,000 (cost 10). Doubling a page’s count adds 1 to its cost, so a hub costs about as much as a few obscure pages.
Popular: cost from popularity
popular turns this around. A page with the most-clicked count costs 1, and each bit less adds
1:
cost = 1 + bits(largest count in the graph) - bits(count of the page)
A page nobody clicked into costs the most, 1 plus the bits of the largest count. As with the niche strategies, a short path through less popular pages can still beat a long detour through popular ones.
The goal and the total
The search returns a path with the lowest total cost over the pages after the source. The goal’s own cost is the same for every path, so it changes nothing.
Search by cost buckets
This is a shortest-path search with a cost on each page instead of on each link: every way into a page costs the same. So the search can grow pages by increasing distance and fix a page’s distance the first time it reaches it. Any later way in comes from a page at least as far.
Costs are small integers (1 to 33), so pages wait in one bucket per distance instead of a priority queue. The search takes the lowest non-empty bucket, expands it in parallel like one level of a breadth-first search, and puts each new page into the bucket for its distance plus its cost. It stops when it reaches the goal. When several paths share the lowest cost, the result is the same on every run, for the same reason as a breadth-first level.
The search goes forward only. A backward side would need a full scan of every link for each
bucket, and there are dozens of buckets. For example, niche from Tour Eiffel to Pikachu
visits about 180,000 pages and takes about 40 ms after the in-link count.
Explore with the clickstream
explore walks level by level like a breadth-first search, so each page shows at its shortest
distance from the start. --strategy picks which page of the level above becomes its parent:
followed(default): the page whose link to it readers click most. Ties, and pages with no clicked link from the level above, keep the first-found parent.first-found: the first page that reached it, see Parallel levels.
With a clickstream, each page shows the clicks of the link from its parent. --order clicks
(default) lists the most clicked links first.
Adding a strategy
Each strategy is one PathStrategy object listed in PathStrategies.All. path --strategy, its
help, the missing-column warnings and the strategies command all read that list, so
PathCommand has no per-strategy code.
The code lives in WikipediaPath.GraphBuilder/Analyze/Paths/:
| Folder | Contents |
|---|---|
Paths/ | The path and strategies commands |
Strategies/ | PathStrategy, IPathSearch, PageCostStrategy, each strategy and the PathStrategies list |
Algorithms/ | The searches (PathSearch, FollowedPathSearch, PageCostPathSearch), PathResult and PageCounts |
A strategy picks an algorithm and the counts it scores with. An algorithm knows nothing about strategies or the command line.
A strategy defines:
| Member | Role |
|---|---|
Name | The --strategy value, lowercase with dashes |
Summary | One line for path --help: what the path goes through |
Details | A few sentences for strategies: how it scores, what each page shows |
Reads | click_count, view_count or none. path warns when the graph lacks one |
Prepare | Counts what the search needs once, and returns an IPathSearch |
IPathSearch.Find runs the search. IPathSearch.Score returns the text printed next to each page
of the result, or null.
Pick the shape that fits:
- A cost per page from one count. Add a
PageCostStrategyentry. It takes a function that returns one count per node (PageCountshas in-links, clicks in, clicks out and views), whether low or high counts are cheap, and the unit printed after each count. It reuses the page costs search, and needs no new class. - Another cost or another search. Subclass
PathStrategyand return your ownIPathSearch.ShortestStrategyandFollowedStrategyare the examples.
Then add the new name to the tables above and in the command reference. The tests check that every strategy has a unique name, a summary and details.
Excluded pages
With --exclude-date-page or --exclude-country, the search never goes through a page of that
kind. The source and the goal can still be one. This works with every strategy, and with
explore.
Development
Run everything inside nix develop.
Build and test
dotnet build
dotnet test
The tests use xUnit v3 on Microsoft.Testing.Platform (set in global.json). They don’t need
MariaDB or a real dump: they write small WGRF files to a temporary directory.
The test folders mirror the source folders: the tests of Analyze/Paths/Algorithms/PathSearch.cs
are in Analyze/Paths/Algorithms/PathSearchTests.cs. Shared helpers live in Support/:
TestGraph writes WGRF files to a temporary directory, and SampleGraphs holds the small graphs
that several test files use.
WikipediaPath.GraphBuilder.Tests/Support/WgrfFile.cs is a small WGRF reader written from the spec only,
separate from WgrfReader. Writer tests use it, so a bug shared by the writer and the reader
still fails a test.
Formatting
Before you commit, check the formatting:
dotnet format --verify-no-changes
Run dotnet format to fix the files.
Warnings
Both projects set TreatWarningsAsErrors. The tool is published with native AOT
(PublishAot), so avoid code that needs runtime reflection. JSON goes through source-generated
contexts, like DumpStatusJsonContext.
NuGet dependencies and Nix
Nix builds offline, so it needs a lock of every NuGet package: deps.json. After you add or
update a package, regenerate it:
nix run .#update-deps
Native build
nix build # result/bin/WikipediaPath.GraphBuilder
Or without Nix:
dotnet publish WikipediaPath.GraphBuilder -c Release -r linux-x64 -o out
Running the build output outside the dev shell
A dotnet build output needs to find the .NET runtime. Outside the dev shell, set
DOTNET_ROOT:
export DOTNET_ROOT=$(dirname "$(readlink -f "$(which dotnet)")")
The AOT binary from nix build does not need it.
Profiling
The dev shell has dotnet-trace, dotnet-counters and perf:
dotnet tool run dotnet-counters monitor -n WikipediaPath.GraphBuilder
dotnet tool run dotnet-trace collect -- ./result/bin/WikipediaPath.GraphBuilder path "Tour Eiffel" "Pikachu"
build --verbose also prints rates, ETA and memory use every few seconds.
Changing the file format
docs/src/spec/wgrf.spec.md is the source of truth. Code that reads or writes WGRF follows it
exactly. If you change the format, change the spec in the same commit, and bump the version when
old files can no longer be read.
Documentation
This book lives in docs/. Preview it with:
mdbook serve docs --open
mdbook build docs writes the HTML to docs/book/, which is ignored by git.
WikipediaPath.GraphBuilder
WikipediaPath.GraphBuilder is the command-line tool of the repository. It builds the WGRF graph
from Wikipedia dumps, then reads it.
WikipediaPath.GraphBuilder <command> [options]
| Command | What it does |
|---|---|
download | Fetches the dumps, the clickstream and Wikidata categories |
decompress | Unpacks the .gz files |
provision | Loads the .sql dumps into MariaDB |
build | Reads MariaDB and writes the .wgrf graph |
info | Summarizes a graph and checks it against the spec |
explore | Shows the pages reachable from one page |
path | Finds a path between two pages: most followed, shortest, popular or niche |
strategies | Describes each path strategy |
Every command has --help.
download
Downloads the Wikipedia table dumps, the clickstream and the Wikidata categories.
WikipediaPath.GraphBuilder download [options]
| Option | Default | Description |
|---|---|---|
-o, --output | dumps | Directory for the files |
--wiki | frwiki | Wiki database name |
--date | latest | Dump run as yyyyMMdd, or latest |
--clickstream | latest | Month as yyyy-MM, latest, or none to skip it |
--mirror | https://dumps.wikimedia.org/ | Base URL of a Wikimedia dumps mirror |
Choosing the dump
With --date latest, the command lists the dump runs on the mirror, newest first, and reads each
run’s dumpstatus.json. It picks the first run where these jobs are done: pagetable,
pagelinkstable, linktargettable, redirecttable and pagepropstable.
With an explicit date, the command fails if one of these jobs is not finished.
Downloading
- Files download one at a time. Wikimedia limits parallel connections per IP.
- Each file goes to
<name>.part, then moves to<name>once its size and SHA-1 match whatdumpstatus.jsonsays. - An interrupted
.partfile resumes with an HTTP range request. - Network errors retry up to 5 times, with a longer wait each time.
- A file already present with the right size is skipped.
Wikidata categories
After the dumps, the command runs one SPARQL query per category on the
Wikidata Query Service and writes
<wiki>-wikidata-categories.tsv:
# Wikidata categories of frwiki articles, queried 2026-09-30T22:25:29Z from https://query.wikidata.org/sparql
Q2151 day
Q2150 day
...
Q750 country
Q16 country
If the file exists, the command does not query again. Delete it to get fresh data.
This data is from the day you run the command, not from the dump date.
decompress
Decompresses every .gz file in a directory.
WikipediaPath.GraphBuilder decompress [options]
| Option | Default | Description |
|---|---|---|
-i, --input | dumps | Directory with the .gz files |
-o, --output | same as --input | Directory for the decompressed files |
-j, --parallelism | number of CPU cores | Files decompressed at the same time |
Gzip decoding can’t be split inside one file, so the work is split by file. The largest files
start first, so the longest job does not start last. With the default dump set, pagelinks takes
most of the time.
Each file is written to <name>.part, then renamed. A file that already exists is skipped. If an
archive is corrupt, its .part file is deleted and the command fails.
The .gz files are kept. Delete them yourself if you need the disk space.
provision
Loads the .sql dumps into MariaDB. Each dump drops its table and creates it again.
WikipediaPath.GraphBuilder provision [options]
| Option | Default | Description |
|---|---|---|
-i, --input | dumps | Directory with the .sql files |
-d, --database | $WPATH_DB_NAME, else wikipedia | Target database. It must exist |
--socket | $MYSQL_UNIX_PORT | MariaDB unix socket |
--client | mariadb | MariaDB command-line client |
--keep-row-format | off | Keep ROW_FORMAT=COMPRESSED from the dumps |
-j, --parallelism | 4 | Tables loaded at the same time |
Start the server first with db-start. See Local database.
How it loads
The command starts one mariadb client per file and streams the file to it. The client parses
the SQL. Progress shows every 10 seconds.
Only files ending in .sql are loaded. The clickstream .tsv is ignored.
Row format
Wikimedia dumps create tables with ROW_FORMAT=COMPRESSED. Compressed pages cost CPU on every
insert, and loading is about twice as slow. By default, the command removes this option from the
CREATE TABLE statements. The tables then use more disk.
Use --keep-row-format if disk space matters more than time.
Time
This step takes hours: the pagelinks dump alone is about 9 GB of SQL. Don’t run it again unless
you have new dumps.
build
Reads the provisioned tables and writes a WGRF graph file.
WikipediaPath.GraphBuilder build [options]
| Option | Default | Description |
|---|---|---|
-o, --output | dumps/graph.wgrf | File to write |
-d, --database | $WPATH_DB_NAME, else wikipedia | Database with the tables |
--socket | $MYSQL_UNIX_PORT | MariaDB unix socket |
--client | mariadb | MariaDB command-line client |
--categories | dumps/frwiki-wikidata-categories.tsv | Categories file from download |
--clickstream | newest dumps/clickstream-frwiki-*.tsv | Decompressed clickstream for the click_count and view_count columns |
-v, --verbose | off | Progress every few seconds, queries, memory, what was dropped |
What it needs
- The tables
page,redirect,linktarget,pagelinksandpage_props. The command stops if one is missing. - The categories file. The command stops if it is missing.
- Optionally, a decompressed clickstream
.tsv. Without--clickstream, the command takes the newestclickstream-frwiki-*.tsvindumps/. If there is none, the graph has noclick_countandview_countcolumns. If you give--clickstreamand the file is missing, the command stops.
Steps
- Read every main-namespace page from
page. - Read redirects from
redirect, then resolve each one to an article. - Read
page_propsto give each article its Wikidata category. - Read the clickstream, if any: every row adds to the views of the page it ends on, and each
linkrow with both titles resolved to articles gives clicks to that pair. - Read
linktargetto map each link target to an article. - Read
pagelinksin primary key order. Rows come grouped by source page, which is node order, so each node’s edges go straight to the file. The edge list is never held in memory. - Write titles, the title index, the click counts and the directories.
From Wikipedia to a graph explains the rules applied in each step.
Output
The file is written to <output>.tmp, then renamed. If the build fails, the .tmp file is
deleted and the old graph stays in place.
The command never writes to the database. See Read-only access from build.
Querying MariaDB
The builder runs each query through the mariadb client with --batch --quick and parses the
tab-separated output. It does not use a .NET database driver.
info
Prints a summary of a WGRF file and checks that it follows the spec.
WikipediaPath.GraphBuilder info [options]
| Option | Default | Description |
|---|---|---|
-i, --input | dumps/graph.wgrf | File to read |
--top | 10 | Entries in the “most links” and “most clicked” rankings |
Output
- Header: version, build date, file size, node, edge and name counts.
- Sections and columns: id, name, offset and size of each region.
- Degrees: mean, median, 99th percentile and maximum of outgoing and incoming links, dead ends and orphans, and how many links go both ways.
- Titles: number of aliases, mean and longest title.
- Categories: articles per Wikidata category.
- Clickstream: edges with clicks, total clicks and total views, when the file has them.
- Rankings: pages with the most outgoing and incoming links, the most viewed pages and the most clicked links.
- Checks: errors and warnings.
Checks
The command reads the whole file (about 15 seconds for French Wikipedia).
- An error means the file breaks the spec, for example an edge that points past the last node. The command exits with code 1.
- A warning means the file breaks a builder rule, for example unsorted or duplicate edges, or self-loops. The command still exits with 0.
When everything is fine, it prints:
Checks (14.6 s)
ok: the file follows the spec and the builder rules.
explore
Shows the pages you can reach from one page, level by level.
WikipediaPath.GraphBuilder explore [title] [options]
| Option | Default | Description |
|---|---|---|
title | Page to start from | |
-i, --input | dumps/graph.wgrf | File to read |
--node | Start from this node id instead of a title | |
-d, --max-depth | 2 | Clicks away from the start page, 0 to 32 |
-n, --max-children | 10 | Pages shown under each page. The rest are counted |
--order | Clicks | Order of child pages: Clicks (most clicked link first), Links (most links first), Title or Id |
-s, --strategy | followed | Parent of each page: followed (most clicked link from the level above) or first-found |
-f, --format | tree | tree for text, dot for Graphviz |
--exclude-date-page | off | Never walk into a date page |
--exclude-country | off | Never walk into a country page |
Example
$ WikipediaPath.GraphBuilder explore Pikachu -d 2 -n 3
Pikachu (node 502244, page_id 1797391)
depth 0: 1 new, 1 reached (0.00 % of the graph)
depth 1: 458 new, 459 reached (0.02 % of the graph)
depth 2: 31,309 new, 31,768 reached (1.14 % of the graph)
Pikachu (458 links, 458 new)
├── Pichu et ses évolutions (104 clicks, 339 links, 7 new)
│ ├── Yōkai (0 clicks, 238 links)
│ ├── Raijū (0 clicks, 164 links)
│ ├── Kami (divinité) (0 clicks, 160 links)
│ └── … 4 more
├── Liste des Pokémon (53 clicks, 193 links, 2 new)
│ ├── Système de gestion d'exceptions (0 clicks, 72 links)
│ └── Dolman (0 clicks, 12 links)
├── Pokémon (45 clicks, 351 links, 84 new)
│ ├── Histoire du jeu vidéo (41 clicks, 498 links)
│ ├── Jeu vidéo de rôle (38 clicks, 220 links)
│ ├── Éponymie (36 clicks, 250 links)
│ └── … 81 more
└── … 455 more
The tree is a shortest-path tree: each page shows once, at its shortest distance from the start.
With --strategy followed, a page sits under the page of the level above whose link to it
readers click most, and “clicks” is the count of that link. A page no link from the level above
was clicked into keeps the first page that reached it, with 0 clicks. --strategy first-found
always keeps the first page, as a plain breadth-first search. On a graph without a clickstream,
both give the same tree and the labels show no clicks. See
Explore with the clickstream.
In Graphviz output, each edge is labeled with its clicks.
Graphviz output
WikipediaPath.GraphBuilder explore Pikachu -d 2 -n 5 -f dot | dot -Tsvg > pikachu.svg
Graphviz is not in the dev shell. Install it yourself if you need it.
The start title follows the same rules as path, see Title matching.
path
Finds a chain of links from one page to another: the one readers follow most, the shortest, or one through popular or little-known pages.
WikipediaPath.GraphBuilder path <from> <to> [options]
| Option | Default | Description |
|---|---|---|
from | Page to start from | |
to | Page to reach | |
-i, --input | dumps/graph.wgrf | File to read |
-s, --strategy | followed | followed, shortest, popular, niche, niche-clicks or niche-views, see below |
--exclude-date-page | off | Never go through a date page (day, year, century, …) |
--exclude-country | off | Never go through a country page |
Strategies
| Strategy | Finds | Each page shows |
|---|---|---|
followed | The links readers click most | clicks on the link to it |
shortest | The fewest clicks | nothing |
popular | A way through pages readers click into most | clicks on links into it |
niche | A way through pages few others link to | in-links |
niche-clicks | A way through pages readers rarely click into | clicks on links into it |
niche-views | A way through pages readers rarely visit | views |
All strategies except shortest and niche need a graph built with a clickstream. Without one,
every count is 0 and the command warns you. Run strategies for how each one
scores a path, and see Path search for the search algorithms.
The path goes to standard output. The search statistics and messages go to standard error.
The command exits with 1 when a title is unknown or when no path exists.
When several best paths exist, the command prints one of them. It is the same one on every run.
Examples
On the 2026-09-01 dump with the 2026-08 clickstream:
$ WikipediaPath.GraphBuilder path "Tour Eiffel" "Pikachu"
Prepared 'followed' in 123 ms.
Searched 181,402 pages in 286 ms.
5 clicks from 'Tour Eiffel' to 'Pikachu':
0. Tour Eiffel
1. Tour métallique de Fourvière (17 clicks on this link)
2. Téléphone mobile (16 clicks on this link)
3. Smartphone (121 clicks on this link)
4. Jeu vidéo (11 clicks on this link)
5. Pikachu (23 clicks on this link)
$ WikipediaPath.GraphBuilder path "Tour Eiffel" "Pikachu" -s shortest
Prepared 'shortest' in 0 ms.
Searched 99,483 pages in 30 ms.
2 clicks from 'Tour Eiffel' to 'Pikachu':
0. Tour Eiffel
1. Jeu vidéo
2. Pikachu
$ WikipediaPath.GraphBuilder path "Tour Eiffel" "Pikachu" -s niche
Prepared 'niche' in 98 ms.
Searched 178,161 pages in 45 ms.
3 clicks from 'Tour Eiffel' to 'Pikachu':
0. Tour Eiffel (2,083 in-links)
1. Légende urbaine (483 in-links)
2. Thème de Lavanville (12 in-links)
3. Pikachu (392 in-links)
followed takes 5 clicks here because nobody clicked Tour Eiffel → Jeu vidéo that month: an
unclicked link costs more than a chain of clicked ones.
niche-clicks and niche-views count a page without clickstream data as 0, the rarest value.
They tend to go through pages the clickstream never measured, such as 1944 en sport.
Title matching
The command tries, in this order:
- The text as you typed it.
- With underscores replaced by spaces (
Tour_Eiffel). - With a capital first letter (
tour Eiffel). - Ignoring case, if every match is the same page.
Redirect names work too. The command tells you when it follows one:
'Paris (France)' redirects to 'Paris'.
If nothing matches, it suggests the closest names.
Excluding pages
--exclude-date-page and --exclude-country need the category column. Graphs built by the
current build always have it. The two pages you give can still be a date or a country.
See Path search for how the search works.
strategies
Describes each path --strategy: what the path goes through, the columns it reads, how it scores
a path and what each printed page shows. It reads no graph.
WikipediaPath.GraphBuilder strategies [name]
| Option | Default | Description |
|---|---|---|
name | Strategy to describe. All of them without it |
$ WikipediaPath.GraphBuilder strategies niche
niche: through pages few others link to.
Reads: links.
Entering a page costs the bit length of its number of in-links, at least 1: 1 for 0 or 1 in-link,
11 for 1,024 to 2,047. The path has the lowest total cost over the pages after the start. Each
page shows its in-links.
The texts come from the strategy definitions in Analyze/Paths/Strategies/PathStrategies.cs,
the same ones path --help summarizes.
Specification
This part holds the formal specification of the files the project writes.
- WGRF file format: the binary graph file written by
buildand read byinfo,exploreandpath.
The specification is the source of truth. When the code and the spec disagree, the code is wrong, or the spec must change in the same commit.
Reading the WGRF spec
- Layout, Header, Section directory, Column directory, Node / Title / ByTitle, Alignment describe the bytes. You need these to write your own reader.
- Builder responsibilities describe what goes into the file: which pages become nodes, how redirects and links are handled, where categories come from. The From Wikipedia to a graph page explains the same rules in plain words.
- Open / deferred lists what is not decided yet. Don’t implement these parts until the spec defines them.
WGRF — Wikipedia-fr Path Graph Binary Format
Status: draft · Version: 1
Read-only, mmap-friendly CSR graph of Wikipedia-fr articles for BFS / shortest-path.
Conventions
- Little-endian.
uint16/uint32/uint64= 2/4/8 bytes. Strings are UTF-8, not terminated. - All offsets are byte offsets from the start of the file.
- Every section and column starts aligned to its element size; the builder pads before it.
Model
Two levels of self-describing tables:
- Section directory — locates the top-level regions (nodes, titles, columns, …). A reader finds every region through this table, never by a hard-coded position.
- Column directory — one section that lists the per-edge / per-node columns. An edge is
not a struct but an index: edge
iistarget_id[i],flags[i], … across parallel columns. Both tables carrybyte_length, so a reader skips any section or column it doesn’t recognize — new data is added without a version bump. Adjacency is CSR:Node[i]marks where nodei’s out-edges start; the sentinelNode[node_count]closes the last node.
Layout
[Header] // 64 bytes, fixed
[Section * section_count] // section directory
[Column * column_count] // one section: the column directory
[Node * (node_count + 1)] // CSR row offsets, id-indexed, + sentinel
[<column data blocks>] // target_id (mandatory) + optional columns, any order
[Title * (node_count + 1)] // id-indexed, + sentinel
[TitleBytes] // packed UTF-8, padded to 4
[ByTitle * by_title_count] // alphabetical search index (canonical + aliases)
Physical order is illustrative; only the directories are authoritative.
Header — 64 bytes
struct Header {
byte[4] magic; // "WGRF"
uint32 version; // 1
uint64 build_date; // Unix seconds, UTC
uint32 node_count;
uint32 reserved0;
uint64 edge_count; // length of edge-domain columns
uint16 section_count;
uint16 reserved1;
uint32 reserved2;
uint64 sections_offset; // -> Section[section_count]
byte[16] reserved;
};
A reader rejects a file whose magic is not WGRF or whose version it does not know: a new
version means existing readers would misread the file. sections_offset is 8-aligned.
Section directory
struct Section { // 24 bytes
uint16 section_id; // see registry
uint16 reserved;
uint32 element_size; // bytes/element; 0 if variable (e.g. title_bytes)
uint64 offset; // start of the section
uint64 byte_length; // total size — enables skipping unknown sections
};
Registry (gaps left for growth):
| id | name | element_size | notes |
|---|---|---|---|
| 0 | columns | 32 | the column directory (see below) |
| 1 | nodes | 4 | Node[node_count + 1] |
| 2 | titles | 4 | Title[node_count + 1] |
| 3 | title_bytes | 0 | packed UTF-8 |
| 4 | by_title | 12 | ByTitle[by_title_count] |
Sections columns, nodes, titles, title_bytes, by_title are all required in v1;
future sections may be optional. count is derived: byte_length / element_size, except the
sentinel arrays which hold node_count + 1.
Column directory (section 0)
struct Column { // 32 bytes
uint16 column_id; // see registry
uint8 domain; // 0 = edge-indexed, 1 = node-indexed
uint8 encoding; // 0 = dense fixed-width
// 1 = sparse pairs (index:uint32, value:uint32)
// 2 = delta+varint (reserved)
uint8 element_size; // bytes/element for dense; 8 (one pair) for sparse;
// 0 if variable
uint8 reserved8;
uint16 reserved16;
uint64 offset;
uint64 byte_length; // enables skipping unknown columns
uint64 count; // element count (dense) or pair count (sparse)
};
Registry:
| id | name | domain | encoding | notes |
|---|---|---|---|---|
| 0 | target_id | edge | dense u32 | mandatory — hot BFS array, stored alone |
| 1 | flags | edge | dense u8 | per-edge bits, meaning TBD |
| 2 | click_count | edge | sparse | clicks from the clickstream; optional |
| 16 | page_id | node | dense u32 | Wikipedia curid; optional |
| 17 | category | node | dense u8 | kind of page, see below; optional |
| 18 | view_count | node | dense u32 | visits from the clickstream; optional |
A reader that cannot find column_id = 0 MUST reject the file. Others are optional. Because
click_count is sparse, an absent edge means “no clickstream data” — no flag needed to tell
that apart from a measured zero.
Sparse columns
A sparse column (encoding = 1) stores only the elements that have a value, as pairs:
struct SparsePair { // 8 bytes
uint32 index; // edge or node index, per the column's domain
uint32 value;
};
element_sizeis 8,countis the number of pairs andbyte_lengthiscount * 8.- Pairs are sorted by strictly ascending
index: no index appears twice. A reader finds one element by binary search. A node’s edges are contiguous, so the pairs of its edges form one contiguous run. indexis belowedge_countfor an edge-domain column, belownode_countfor a node-domain one. Likefirst_edge, it assumes edge indices fit in 2^32.- An index without a pair has no value. That is not the same as a value of 0.
click_count values
Number of times readers followed the link of this edge during one month, from the Wikipedia clickstream. One file uses one month. Only edges the clickstream measured have a pair, so most edges have none. When the column is absent, the file was built without clickstream data.
view_count values
Number of times readers reached the page during the same month, from any referer: another article, a search engine, another site or no referer. It sums every clickstream row that ends on the page. The clickstream leaves out the rarest pairs, so this is a lower bound of the page views, not an exact count. When the column is absent, the file was built without clickstream data.
category values
One byte per node naming what kind of page it is. A page has at most one category.
| value | name | example |
|---|---|---|
| 0 | none | any page not listed below |
| 1 | day | 14 juillet |
| 2 | date | 10 mai 1981 |
| 3 | month | Janvier |
| 4 | month_of_year | Janvier 1913 |
| 5 | year | 1913, 44 av. J.-C. |
| 6 | decade | Années 1910 |
| 7 | century | XIXe siècle |
| 8 | millennium | IIe millénaire |
| 9 | year_in_topic | 1913 en sport |
| 10 | country | France, Écosse |
Values 1 to 8 are date pages. year_in_topic is a chronology of one field for one period,
not a date page. country covers historical states, empires and constituent countries too, so
République démocratique allemande is one. Values 11 to 255 are reserved: a reader treats them
as none. When the column is absent, no page has a known category; that is not the same as
every page being none.
Node / Title / ByTitle
struct Node { uint32 first_edge; }; // index into edge-domain columns
struct Title { uint32 first_byte; }; // offset into title_bytes
struct ByTitle { // 12 B, sorted alphabetically by name
uint32 name_first_byte; // -> title_bytes
uint32 name_length;
uint32 node_id; // canonical node this name resolves to
};
out_degree(i) = Node[i+1].first_edge - Node[i].first_edge.- Title length of node
i=Title[i+1].first_byte - Title[i].first_byte. by_title_count >= node_count(canonical titles + searchable redirect aliases; many entries may share onenode_id). Name→id is a binary search comparing againsttitle_bytes.Titlestays id-ordered for the id→name direction used during traversal.- “Alphabetically” means ordinal comparison of the UTF-8 bytes (no case folding, no collation),
shorter name first when one is a prefix of the other; equal names are ordered by
node_id. - Alias names live in
title_bytesafter the canonical titles, pastTitle[node_count], so theTitlesentinel still closes the last canonical title. uint32widths onfirst_edge/first_byteassume the arrays fit in 2^32; confirm from dump statistics.
Alignment
Header is 64 (8-aligned). Because every region has an explicit offset, the builder pads before
each so it starts aligned to its element: Section table → 8, Column table → 8, nodes → 4,
each dense column → its element_size, each sparse column → 4, titles → 4, title_bytes → padded to 4 before
by_title, by_title → 4. What precedes a region never affects its alignment.
Padding bytes and every reserved* field are zero. A section’s or column’s byte_length covers
its data only, never the padding after it.
Builder responsibilities (not in the file)
-
Nodes: main-namespace (
page_namespace = 0) pages that are not redirects. Node ids follow ascendingpage_id. -
Titles: stored in their displayed form: the underscores of
page_titlebecome spaces (Tour_Eiffel→Tour Eiffel). Aliases use the same form. -
Redirects: resolve each to its canonical target, rewrite edges to canonical ids, drop redirects as nodes — the file holds only real articles. Optionally append a redirect’s title to
title_bytesand add aByTitleentry pointing at the canonical id. The v1 builder adds an alias for every resolved redirect. It follows redirect chains up to 8 hops. A redirect that loops, runs longer, points at a missing page, at another namespace or at another wiki (rd_interwiki) is dropped: no alias, and links to it are dropped like red links. -
Edges: a link becomes an edge when both ends resolve to a node. Each node’s targets are sorted by ascending node id, without duplicates (two links can resolve to one article through redirects) and without self-loops.
-
page_id: if the
page_idcolumn is present, the page_id→node_id lookup is built at load. The v1 builder always writes it. -
category: taken from Wikidata. The article’s item comes from
page_props(pp_propname = 'wikibase_item'), and its category from the item’s “instance of” (P31) statements, matched directly, without following “subclass of” (P279):category the item is an instance of dayQ14795564 (point in time with respect to recurrent timeframe) and is part of (P361) an instance of Q47018901 (calendar month) dateQ47150325 (calendar day of a given year) monthQ47018901 (calendar month) month_of_yearQ47018478 (calendar month of a given year) yearQ3186692 (calendar year), Q577 (year) or Q29964144 (year BC) decadeQ39911 (decade) centuryQ578 (century) millenniumQ36507 (millennium) year_in_topicQ18340514 (events in a specific year or time period) countryQ6256 (country), Q3624078 (sovereign state), Q3024240 (historical country), Q48349 (empire) or Q1520223 (constituent country) An item that matches several rows gets the smallest value. Redirects keep no category of their own. Wikidata is queried live, so its statements can be newer than the dump. The v1 builder always writes the column.
-
click_count: taken from a monthly clickstream file (
clickstream-<wiki>-<yyyy-MM>.tsv, rows ofprev,curr,type,n). Only rows oftype = linkcount.prevandcurrare resolved like link targets: by title, through redirects, to a node. A row whose titles don’t both resolve, or whose two nodes have no edge between them in the file, is dropped. Rows that resolve to the same edge (through different redirects) add up, capped at 2^32 - 1. The clickstream month can differ from the dump date, so some rows name links the dump no longer has. The v1 builder writes the column when a clickstream file is available, and leaves it out otherwise. -
view_count: taken from the same clickstream file as
click_count. Every row counts, whatever itstype.curris resolved like a link target; a row whosecurrdoesn’t resolve is dropped. Rows that resolve to the same node add up, capped at 2^32 - 1. The v1 builder writes the column exactly when it writesclick_count.
Open / deferred
- Reverse (bidirectional) index — not in the file; additive as a new section + columns.
uint32field widths (first_edge,first_byte) pending dump statistics.- Edge compression (
encoding = 2, delta+varint ontarget_id) — reserved, unspecified. flagsbit meanings — TBD.