Wicked Smart Data
LearnInsightsAboutContact
Sign InLet's Build
LearnInsightsAboutContact
Sign InLet's Build
Wicked Smart Data

Intelligence, automation, and expert execution — plus an elite library of free knowledge. We turn complexity into competitive advantage.

Start a conversation

Platform

  • Learning Paths
  • Insights
  • RSS Feed

Company

  • About
  • Contact
  • Work With Us

Legal

  • Privacy Policy
  • Terms of Service

© 2026 Wicked Smart Data. All rights reserved.

Intelligence · Automation · Advantage

All Insights
Power Query

Implementing Custom Graph Traversal and Network Analysis Pipelines in Power Query M

Learn how to build graph algorithms — adjacency lists, BFS shortest paths, and connected component detection — entirely in Power Query M. This hands-on lesson uses a real supplier network scenario to teach you techniques most analysts think require Python.

⚡ Practitioner19 min readDec 2, 2026Updated Dec 2, 2026
Implementing Custom Graph Traversal and Network Analysis Pipelines in Power Query M
On this page
  • Introduction
  • Prerequisites
  • The Dataset: A Supplier Relationship Network
  • Step 1: Building the Adjacency List
  • Step 2: Implementing Breadth-First Search for Shortest Paths
  • Step 3: Connected Component Detection
  • Step 4: Wrapping Everything into Reusable Functions
  • Hands-On Exercise: Identifying At-Risk Supply Chains
  • Common Mistakes & Troubleshooting
  • Mistake 1: Forgetting to make edges undirected
  • Mistake 2: Infinite loops in List.Generate
  • Mistake 3: `Record.FromList` field name conflicts
  • Mistake 4: Performance collapse on large graphs
  • Mistake 5: Treating BFS output as a persistent structure
  • Performance Implications and When to Use This Approach
  • Summary & Next Steps

Implementing Custom Graph Traversal and Network Analysis Pipelines in Power Query M

Introduction

Picture this: your company has acquired three smaller firms, and you've inherited their combined customer database. The sales team needs to know which accounts are connected — same parent company, shared billing addresses, overlapping contacts — so they don't accidentally send competing pitches to subsidiaries of the same enterprise. The data lives in a flat edge table: AccountA, AccountB, RelationshipType. It's a graph problem, and your tooling is Power Query.

Most analysts hit this wall and immediately reach for Python or R. But if your data is already in Power BI or Excel, and your stakeholders expect a refreshable solution that doesn't require a Python runtime, you need to solve it in M. The good news is that M is expressive enough to implement genuine graph algorithms — adjacency list construction, breadth-first traversal for shortest paths, and union-find connected component detection — without leaving the query editor.

By the end of this lesson, you'll have a working, copy-paste-ready graph analysis pipeline built entirely in M. You'll understand not just the code, but why each piece works the way it does, including where M's evaluation model creates unique constraints you won't find in procedural languages.

What you'll learn:

  • How to build an adjacency list from a raw edge table in M
  • How to implement iterative breadth-first search (BFS) for shortest path resolution
  • How to detect connected components using a label-propagation approach
  • How to structure recursive and iterative patterns safely within M's functional model
  • Performance trade-offs and when this approach is appropriate vs. pushing the work upstream

Prerequisites

You should be comfortable with M's core data structures — lists, records, and tables — and have written at least a few custom functions. If you haven't worked through list and record operations in M or writing custom M functions from scratch, review those first. You should also understand how List.Accumulate and List.Generate work, since those are the backbone of iteration in M. A solid grounding in advanced M iterators, accumulators, and recursive patterns will make this lesson considerably easier to follow.


The Dataset: A Supplier Relationship Network

We'll work with a realistic scenario throughout: a procurement team managing a supplier network. Each row in SupplierEdges represents a business relationship between two supplier IDs. The relationships are undirected — if Supplier A ships to Supplier B, B also ships to A for our analysis purposes.

Here's our starting edge table (you can paste this into a blank query using Table.FromRecords):

SupplierID_A | SupplierID_B | RelationshipType
-------------|--------------|------------------
S001         | S002         | Subcontractor
S001         | S003         | Subsidiary
S002         | S004         | Subcontractor
S005         | S006         | Partner
S007         | S005         | Subsidiary
S008         | S009         | Partner
S010         | S011         | Subcontractor
S009         | S010         | Subsidiary

This graph has three connected components: {S001, S002, S003, S004}, {S005, S006, S007}, and {S008, S009, S010, S011}. That's what we're going to prove computationally.


Step 1: Building the Adjacency List

An adjacency list maps each node to its direct neighbors. It's the foundational structure for every graph algorithm we'll implement. In M, the natural representation is a list of records, or a table with a node column and a neighbors column.

Create a new blank query and name it BuildAdjacencyList. Here's the full implementation:

let
    // Raw edge data - in production this would reference your actual query
    RawEdges = Table.FromRecords({
        [A = "S001", B = "S002"], [A = "S001", B = "S003"],
        [A = "S002", B = "S004"], [A = "S005", B = "S006"],
        [A = "S007", B = "S005"], [A = "S008", B = "S009"],
        [A = "S010", B = "S011"], [A = "S009", B = "S010"]
    }),

    // Make edges undirected by unioning A->B with B->A
    ForwardEdges = Table.SelectColumns(RawEdges, {"A", "B"}),
    ReverseEdges = Table.RenameColumns(
        Table.SelectColumns(RawEdges, {"B", "A"}),
        {{"B", "A"}, {"A", "B"}}
    ),
    AllEdges = Table.Combine({ForwardEdges, ReverseEdges}),

    // Collect all unique nodes
    AllNodes = List.Distinct(
        List.Combine({
            Table.Column(RawEdges, "A"),
            Table.Column(RawEdges, "B")
        })
    ),

    // Build adjacency list: for each node, find all neighbors
    AdjacencyList = List.Transform(
        AllNodes,
        (node) =>
            [
                Node     = node,
                Neighbors = Table.Column(
                    Table.SelectRows(AllEdges, each _[A] = node),
                    "B"
                )
            ]
    ),

    // Convert to table for easier downstream use
    AdjTable = Table.FromRecords(AdjacencyList)
in
    AdjTable

Let's break down what's happening. Making edges undirected is critical — we union the forward and reverse direction so that when we look up S002's neighbors, we find both S001 (via reverse) and S004 (via forward). The List.Transform over AllNodes is where the adjacency list gets built: for each node, we filter AllEdges to rows where column A matches that node, then extract column B as the neighbors list.

The result is a two-column table: Node (text) and Neighbors (a list of text values). This is exactly the structure BFS needs.

Key insight

M stores lists inside table cells natively. This isn't a workaround — it's the idiomatic way to represent nested structures like adjacency lists. If you've worked with advanced table operations in M, you've seen this pattern with Table.Group. The adjacency list is just a grouped version of the edge table.


Step 2: Implementing Breadth-First Search for Shortest Paths

BFS is the standard algorithm for finding the shortest path between two nodes in an unweighted graph. The challenge in M is that BFS is inherently iterative — you maintain a frontier queue, expand it layer by layer, and stop when you reach the target. M doesn't have mutable state, so we simulate the queue using List.Generate.

List.Generate is M's closest analog to a while loop. It takes four arguments: an initial state, a condition to continue, a next-state function, and an optional selector. We'll use it to evolve the BFS frontier.

Create a new query named ShortestPath:

let
    // Reference the adjacency list we built
    AdjTable = BuildAdjacencyList,

    // Helper: look up neighbors for a given node
    GetNeighbors = (node as text) as list =>
        let
            MatchRow = Table.SelectRows(AdjTable, each _[Node] = node),
            Result   = if Table.RowCount(MatchRow) = 0
                       then {}
                       else MatchRow{0}[Neighbors]
        in
            Result,

    // BFS implementation using List.Generate
    // State: [Frontier = list of paths being explored, Visited = list of visited nodes]
    BFS = (startNode as text, targetNode as text) as any =>
        let
            InitialState = [
                Frontier = {{startNode}},   // Each path is a list of nodes
                Visited  = {startNode},
                Found    = null
            ],

            BFSSteps = List.Generate(
                () => InitialState,
                // Continue while frontier is non-empty and target not found
                (state) => List.Count(state[Frontier]) > 0 and state[Found] = null,
                // Expand frontier: for each path, extend with unvisited neighbors
                (state) =>
                    let
                        CurrentFrontier = state[Frontier],
                        CurrentVisited  = state[Visited],

                        // Expand each path in the frontier
                        NewPaths = List.Combine(
                            List.Transform(
                                CurrentFrontier,
                                (path) =>
                                    let
                                        LastNode  = List.Last(path),
                                        Neighbors = GetNeighbors(LastNode),
                                        // Only expand to unvisited neighbors
                                        NewNeighbors = List.Select(
                                            Neighbors,
                                            each not List.Contains(CurrentVisited, _)
                                        ),
                                        Extended = List.Transform(
                                            NewNeighbors,
                                            (n) => List.Combine({path, {n}})
                                        )
                                    in
                                        Extended
                            )
                        ),

                        // Check if any new path reached the target
                        FoundPath = List.Select(
                            NewPaths,
                            each List.Last(_) = targetNode
                        ),

                        NewVisited = List.Distinct(
                            List.Combine({
                                CurrentVisited,
                                List.Transform(NewPaths, each List.Last(_))
                            })
                        )
                    in
                        [
                            Frontier = if List.Count(FoundPath) > 0 then {} else NewPaths,
                            Visited  = NewVisited,
                            Found    = if List.Count(FoundPath) > 0 then FoundPath{0} else null
                        ]
            ),

            // Extract the last state from the generator
            FinalState = List.Last(BFSSteps),

            Result = if FinalState[Found] = null
                     then "No path found"
                     else FinalState[Found]
        in
            Result,

    // Test: shortest path from S001 to S004
    TestPath = BFS("S001", "S004"),
    // Expected: {S001, S002, S004}

    // Test: shortest path from S001 to S006 (different component)
    TestNoPath = BFS("S001", "S006")
in
    [PathFound = TestPath, NoPathResult = TestNoPath]

This deserves careful reading. The BFS state carries three fields: Frontier (a list of in-progress paths), Visited (nodes already explored), and Found (the solution path, once discovered). Each iteration of List.Generate replaces the state with a new record where each frontier path is extended by one hop.

The inner List.Transform over CurrentFrontier returns a list of lists — one per path, containing its extensions. List.Combine flattens those into a single list of paths. We then filter NewPaths to see if any of them end at targetNode.

Warning

BFS in M has real performance limits. Each List.Generate iteration calls GetNeighbors once per path in the frontier. In a dense graph with hundreds of nodes, the frontier can grow exponentially. This approach is appropriate for graphs with fewer than a few hundred nodes. For larger graphs, you need a database-side solution or a Python visual.

When you run this, TestPath returns {"S001", "S002", "S004"} — the correct two-hop shortest path. TestNoPath returns "No path found" because S001 and S006 are in different components.


Step 3: Connected Component Detection

Finding connected components is arguably more valuable for most business problems than shortest paths. It answers the question: "Which nodes belong to the same cluster, with no requirement to find a specific path?"

The classic approach is union-find (also called disjoint set union), but that requires mutable arrays. In M, we use label propagation: assign each node its own label, then repeatedly propagate the minimum label among neighbors until labels stabilize.

This is iterative and naturally fits List.Generate. Create a new query named ConnectedComponents:

let
    AdjTable = BuildAdjacencyList,

    // Extract all nodes as a list
    AllNodes = AdjTable[Node],

    // Helper to get neighbors
    GetNeighbors = (node as text) as list =>
        let
            MatchRow = Table.SelectRows(AdjTable, each _[Node] = node)
        in
            if Table.RowCount(MatchRow) = 0
            then {}
            else MatchRow{0}[Neighbors],

    // Initial labeling: each node is its own component
    // State: a list of records [Node, Label]
    InitialLabels = List.Transform(
        AllNodes,
        (n) => [Node = n, Label = n]
    ),

    // One propagation pass: each node takes the minimum label among itself + neighbors
    PropagateOnce = (labels as list) as list =>
        let
            // Build a lookup: node -> current label
            LabelLookup = Record.FromList(
                List.Transform(labels, each _[Label]),
                List.Transform(labels, each _[Node])
            ),

            NewLabels = List.Transform(
                labels,
                (entry) =>
                    let
                        CurrentNode      = entry[Node],
                        CurrentLabel     = entry[Label],
                        NeighborNodes    = GetNeighbors(CurrentNode),
                        // Get labels of all neighbors (default to their own name if missing)
                        NeighborLabels   = List.Transform(
                            NeighborNodes,
                            (n) => Record.FieldOrDefault(LabelLookup, n, n)
                        ),
                        AllLabels        = List.Combine({{CurrentLabel}, NeighborLabels}),
                        // Minimum label propagates (alphabetical minimum)
                        MinLabel         = List.Min(AllLabels)
                    in
                        [Node = CurrentNode, Label = MinLabel]
            )
        in
            NewLabels,

    // Run propagation until labels stabilize
    // We use List.Generate with a convergence check
    PropagationSteps = List.Generate(
        () => [Labels = InitialLabels, Converged = false, Iteration = 0],
        (state) => not state[Converged],
        (state) =>
            let
                NewLabels  = PropagateOnce(state[Labels]),
                // Check if any label changed
                HasChanged = List.AnyTrue(
                    List.Transform(
                        List.Zip({state[Labels], NewLabels}),
                        (pair) => pair{0}[Label] <> pair{1}[Label]
                    )
                )
            in
                [
                    Labels     = NewLabels,
                    Converged  = not HasChanged,
                    Iteration  = state[Iteration] + 1
                ]
    ),

    FinalState    = List.Last(PropagationSteps),
    FinalLabels   = FinalState[Labels],
    IterationCount = FinalState[Iteration],

    // Convert to table
    ComponentTable = Table.FromRecords(FinalLabels),

    // Add iteration count as metadata for debugging
    AnnotatedResult = Table.AddColumn(
        ComponentTable,
        "IterationsToConverge",
        each IterationCount
    )
in
    AnnotatedResult

The key insight here is in PropagateOnce. We build a Record.FromList lookup — essentially a dictionary — mapping each node name to its current label. Then for each node, we gather the labels of all its neighbors, combine them with its own label, and take the minimum. After enough passes, all nodes in the same component converge to the same minimum label (which happens to be the alphabetically earliest node ID in the component).

The convergence check uses List.Zip to pair up old and new label lists element-by-element, then checks if any pair differs. When no pair differs, Converged becomes true and List.Generate stops.

Note

Label propagation is not guaranteed to converge in a fixed number of steps for all graph topologies, but for undirected graphs it converges in at most diameter(graph) iterations — typically very fast. The Iteration counter in the state lets you verify this in production.

Running this against our supplier data produces:

Node Label IterationsToConverge
S001 S001 3
S002 S001 3
S003 S001 3
S004 S001 3
S005 S005 3
S006 S005 3
S007 S005 3
S008 S008 3
S009 S008 3
S010 S008 3
S011 S008 3

Three distinct labels — three connected components. Exactly right.


Step 4: Wrapping Everything into Reusable Functions

Hardcoded node lists and inline edge tables don't belong in production. Let's refactor our work into parameterized functions that accept any edge table. This is where the patterns from writing custom M functions in Power Query pay off.

Create a query named GraphFunctions that returns a record of functions:

let
    // Function 1: Build adjacency list from an edge table
    fnBuildAdjacencyList = (EdgeTable as table, ColA as text, ColB as text) as table =>
        let
            ColA_Values = Table.Column(EdgeTable, ColA),
            ColB_Values = Table.Column(EdgeTable, ColB),
            ForwardEdges = Table.SelectColumns(EdgeTable, {ColA, ColB}),
            ReverseEdges = Table.RenameColumns(
                Table.SelectColumns(EdgeTable, {ColB, ColA}),
                {{ColB, ColA}, {ColA, ColB}}
            ),
            AllEdges  = Table.Combine({ForwardEdges, ReverseEdges}),
            AllNodes  = List.Distinct(List.Combine({ColA_Values, ColB_Values})),
            AdjList   = List.Transform(
                AllNodes,
                (node) =>
                    [
                        Node = node,
                        Neighbors = Table.Column(
                            Table.SelectRows(AllEdges, each Record.Field(_, ColA) = node),
                            ColB
                        )
                    ]
            )
        in
            Table.FromRecords(AdjList),

    // Function 2: Shortest path using BFS
    fnShortestPath = (AdjTable as table, StartNode as text, TargetNode as text) as any =>
        let
            GetNeighbors = (node as text) as list =>
                let
                    Match = Table.SelectRows(AdjTable, each _[Node] = node)
                in
                    if Table.RowCount(Match) = 0 then {} else Match{0}[Neighbors],

            InitialState = [
                Frontier = {{StartNode}},
                Visited  = {StartNode},
                Found    = null
            ],
            BFSSteps = List.Generate(
                () => InitialState,
                (s) => List.Count(s[Frontier]) > 0 and s[Found] = null,
                (s) =>
                    let
                        NewPaths = List.Combine(List.Transform(s[Frontier], (path) =>
                            let
                                Last  = List.Last(path),
                                Nbrs  = List.Select(GetNeighbors(Last),
                                            each not List.Contains(s[Visited], _)),
                                Ext   = List.Transform(Nbrs, (n) => List.Combine({path, {n}}))
                            in Ext
                        )),
                        Hit      = List.Select(NewPaths, each List.Last(_) = TargetNode),
                        NewVis   = List.Distinct(List.Combine({s[Visited],
                                       List.Transform(NewPaths, each List.Last(_))}))
                    in
                        [
                            Frontier = if List.Count(Hit) > 0 then {} else NewPaths,
                            Visited  = NewVis,
                            Found    = if List.Count(Hit) > 0 then Hit{0} else null
                        ]
            ),
            Final = List.Last(BFSSteps)
        in
            if Final[Found] = null then null else Final[Found],

    // Function 3: Connected components via label propagation
    fnConnectedComponents = (AdjTable as table) as table =>
        let
            AllNodes    = AdjTable[Node],
            GetNeighbors = (node as text) =>
                let Match = Table.SelectRows(AdjTable, each _[Node] = node)
                in if Table.RowCount(Match) = 0 then {} else Match{0}[Neighbors],
            InitLabels  = List.Transform(AllNodes, (n) => [Node = n, Label = n]),
            Propagate   = (labels as list) =>
                let
                    Lookup   = Record.FromList(
                                   List.Transform(labels, each _[Label]),
                                   List.Transform(labels, each _[Node])
                               ),
                    NewLbls  = List.Transform(labels, (e) =>
                                   let
                                       Nbrs  = GetNeighbors(e[Node]),
                                       NLbls = List.Transform(Nbrs,
                                                   (n) => Record.FieldOrDefault(Lookup, n, n)),
                                       All   = List.Combine({{e[Label]}, NLbls})
                                   in [Node = e[Node], Label = List.Min(All)]
                               )
                in NewLbls,
            Steps = List.Generate(
                () => [Labels = InitLabels, Converged = false],
                (s) => not s[Converged],
                (s) =>
                    let
                        New  = Propagate(s[Labels]),
                        Same = not List.AnyTrue(List.Transform(
                                   List.Zip({s[Labels], New}),
                                   (p) => p{0}[Label] <> p{1}[Label]
                               ))
                    in [Labels = New, Converged = Same]
            ),
            Final = List.Last(Steps)[Labels]
        in
            Table.FromRecords(Final)
in
    [
        BuildAdjacencyList   = fnBuildAdjacencyList,
        ShortestPath         = fnShortestPath,
        ConnectedComponents  = fnConnectedComponents
    ]

Now any other query can call GraphFunctions[BuildAdjacencyList](MyEdgeTable, "SourceID", "TargetID") without duplicating logic. This follows the building a reusable function library in Power Query pattern and makes your graph toolkit shareable across workbooks.


Hands-On Exercise: Identifying At-Risk Supply Chains

Let's put it all together on a real scenario. Your procurement team has a table SupplierEdges with columns SupplierA, SupplierB, and a list of "critical suppliers" — nodes whose removal would isolate others. Your task:

  1. Build the adjacency list from SupplierEdges
  2. Identify which connected component each supplier belongs to
  3. For each critical supplier, find the shortest path from your company's root node (S000) to that supplier

Step 1 — Wire up your data:

let
    // Replace with your actual source
    SupplierEdges = Table.FromRecords({
        [SupplierA = "S000", SupplierB = "S001"],
        [SupplierA = "S000", SupplierB = "S005"],
        [SupplierA = "S001", SupplierB = "S002"],
        [SupplierA = "S001", SupplierB = "S003"],
        [SupplierA = "S002", SupplierB = "S004"],
        [SupplierA = "S005", SupplierB = "S006"],
        [SupplierA = "S007", SupplierB = "S005"],
        [SupplierA = "S008", SupplierB = "S009"],
        [SupplierA = "S010", SupplierB = "S011"],
        [SupplierA = "S009", SupplierB = "S010"]
    }),

    GF  = GraphFunctions,
    Adj = GF[BuildAdjacencyList](SupplierEdges, "SupplierA", "SupplierB"),
    CC  = GF[ConnectedComponents](Adj),

    // Find shortest path to each critical supplier
    CriticalSuppliers = {"S004", "S006", "S011"},
    Paths = List.Transform(
        CriticalSuppliers,
        (target) =>
            [
                Target = target,
                Path   = GF[ShortestPath](Adj, "S000", target),
                Hops   = if GF[ShortestPath](Adj, "S000", target) = null
                         then null
                         else List.Count(GF[ShortestPath](Adj, "S000", target)) - 1
            ]
    ),

    PathTable     = Table.FromRecords(Paths),
    // Convert path lists to readable strings
    PathTableFinal = Table.TransformColumns(
        PathTable,
        {"Path", each if _ = null then "Unreachable" else Text.Combine(_, " → ")}
    )
in
    PathTableFinal

The expected output:

Target Path Hops
S004 S000 → S001 → S002 → S004 3
S006 S000 → S005 → S006 2
S011 Unreachable null

S011 is unreachable because it's in a disconnected component (S008–S009–S010–S011 never connects to S000 in this dataset). That's exactly the kind of insight a supply chain team needs.

Tip

Call GF[ShortestPath] only once per target by storing the result in a let binding inside the List.Transform lambda. The code above calls it twice (once for Path, once for Hops). In production, compute the path once and derive Hops from it using List.Count.


Common Mistakes & Troubleshooting

Mistake 1: Forgetting to make edges undirected

If you only use the forward edges A → B, then looking up S002's neighbors won't return S001. Your BFS will miss paths that require traversing an edge "backwards." Always union forward and reverse edges before building the adjacency list.

Mistake 2: Infinite loops in List.Generate

If your convergence condition never becomes true — usually because of a bug in the change-detection logic — List.Generate will run indefinitely (or until Power Query times out). Add a maximum iteration guard:

(s) => not s[Converged] and s[Iteration] < 100

This caps propagation at 100 rounds. For any real-world undirected graph, convergence should happen in far fewer rounds.

Mistake 3: `Record.FromList` field name conflicts

When building the label lookup with Record.FromList, if two nodes have the same name (a data quality issue), you'll get an error because record field names must be unique. Add a deduplication step on node IDs before building the lookup, or switch to a table-based lookup using Table.SelectRows.

Mistake 4: Performance collapse on large graphs

The GetNeighbors helper calls Table.SelectRows on every invocation. If called hundreds of times per BFS iteration, this gets expensive fast. For graphs larger than ~200 nodes, buffer the adjacency table first:

BufferedAdj = Table.Buffer(AdjTable),

Review caching strategies in M for a deeper treatment of when and how to buffer intermediate tables.

Warning

Power Query's lazy evaluation means GetNeighbors doesn't cache its result between calls. If you call GF[ShortestPath](Adj, "S000", "S004") and GF[ShortestPath](Adj, "S000", "S006") in the same query, the adjacency table gets re-evaluated twice unless you buffer it. This is a fundamental aspect of how M evaluates queries.

Mistake 5: Treating BFS output as a persistent structure

The list of paths in BFS's Frontier grows with each iteration. In a wide, shallow graph, you can have thousands of active paths simultaneously. If you're hitting memory pressure, consider switching from full-path tracking to a simple parent-pointer approach — store [Node, Parent, Depth] instead of full path lists, then reconstruct the path afterward by walking back through parent pointers.


Performance Implications and When to Use This Approach

Let's be direct about the ceiling here. M runs in-memory within Power Query's evaluation engine — it's not Python's NetworkX or a graph database. Practically:

Graph Size Adjacency List BFS Shortest Path Connected Components
< 100 nodes Fast Fast Fast
100–500 nodes Fast Acceptable Acceptable
500–2000 nodes Acceptable Slow Slow
> 2000 nodes Avoid Avoid Consider SQL/Python

If your graph is large, the right move is to do the computation upstream. Push it to SQL Server (which has recursive CTEs), to a Python step in Dataflow Gen2, or to a graph database. Then import the already-computed component labels into Power Query. The techniques here shine when your graph is small-to-medium, your data is already in Power Query, and you need a refreshable solution without adding infrastructure.

Key insight

The adjacency list and connected components pipeline are cheaper than BFS because they don't track full paths. If you only need "which component does each node belong to" — the most common business question — skip BFS entirely and just run connected components. It's significantly faster.


Summary & Next Steps

You've built three distinct graph analysis capabilities in pure M:

  • An adjacency list builder that works with any edge table, handling both directed and undirected graphs
  • A BFS shortest path resolver that uses List.Generate to simulate queue-based traversal within M's functional model
  • A connected component detector using label propagation and convergence detection

The key architectural insight is that M's iterative tools — List.Generate, List.Accumulate, List.Transform — are powerful enough to implement classic graph algorithms when you frame the problem as evolving state rather than mutating variables.

Where to go from here:

  • Add edge weights and implement Dijkstra's algorithm. The BFS frontier becomes a priority queue, which you can approximate by sorting NewPaths by accumulated cost after each step.
  • Extend connected components to identify articulation points — nodes whose removal splits a component. These are your "critical suppliers."
  • Explore error handling patterns in M to make your graph functions production-safe against malformed edge tables, duplicate node IDs, and null values.
  • If your edge data lives in a JSON API response, combine this pipeline with advanced JSON and XML processing in M to extract the edge list dynamically before feeding it to the graph functions.

Graph problems aren't exotic edge cases in data work. Supply chains, org hierarchies, account relationships, network topologies — they're everywhere. Now you have the tools to tackle them without leaving Power Query.

Work With Us

From insight to implementation

Reading is the start. When you're ready to build the data, automation, or AI systems behind it, our team turns strategy into shipped results.

Let's Build

Advanced M Language

Previous

Understanding the M Let Expression: Structuring Multi-Step Transformations with Named Variables and In Expressions

Related Insights

Power QueryPractitioner

Connecting to and Refreshing Data from Microsoft Access Databases in Power Query: Tables, Queries, and Credential Management

25 min
Power QueryFoundation

Understanding the M Let Expression: Structuring Multi-Step Transformations with Named Variables and In Expressions

15 min
Power QueryFoundation

Replacing Values and Fixing Inconsistent Entries in Power Query: Standardizing Categories, Codes, and Labels

16 min

On this page

  • Introduction
  • Prerequisites
  • The Dataset: A Supplier Relationship Network
  • Step 1: Building the Adjacency List
  • Step 2: Implementing Breadth-First Search for Shortest Paths
  • Step 3: Connected Component Detection
  • Step 4: Wrapping Everything into Reusable Functions
  • Hands-On Exercise: Identifying At-Risk Supply Chains
  • Common Mistakes & Troubleshooting
  • Mistake 1: Forgetting to make edges undirected
  • Mistake 2: Infinite loops in List.Generate
  • Mistake 3: `Record.FromList` field name conflicts
  • Mistake 4: Performance collapse on large graphs
  • Mistake 5: Treating BFS output as a persistent structure
  • Performance Implications and When to Use This Approach
  • Summary & Next Steps