Search⌘ K
AI Features

Code a “Hello World” Graph

Explore how to create and query a basic Hello World graph in Elixir using the built-in :digraph Erlang library. Learn to add vertices and edges and retrieve paths through a guided IEx session. This lesson introduces foundational graph operations with no setup required, preparing you for more advanced graph handling in Elixir.

Elixir graph packages

As Elixir programmers, it’s only natural to wonder what kind of support Elixir has for working with graph technologies. Quite a bit as it turns out. We’ll see a growing number of Elixir graph packages that have been in active development for some time now. And these address all of the major graph types.

We’ll develop a project that will allow us to explore some of the main graph databases, graph query languages, and graph models. We’ll also look at interchanging between graph types and transforming from one type to another.

But let’s try first something out of the box—no setup required.

Elixir comes with built-in graph support. We can use the Erlang library :digraph that ships with the Elixir distribution. Let’s use this to string a couple of words together.

Steps to create the “Hello World” graph

XML
$ iex
iex> import :digraph
iex> g = new
iex> v1 = add_vertex(g, "Hello")
iex> v2 = add_vertex(g, "World")
iex> get_path(g, v1, v2)
iex> add_edge(g, v1, v2)
iex> get_path(g, v1, v2)

Explanation

  • Lines 1–2: We start with firing up an IEx session and importing the library.

  • Line 4: We create a new graph, g.

  • Lines 6–7: We add vertices to the graph.

  • Line 9: We get the path between the vertices. This would return false because we have not defined any edges in our graph.

  • Line 11: We add edges to our graph.

  • Line 13: We run get_path(g, v1, v2) again to get the correct path between the vertices.

Activity

The following terminal runs an IEx session. Try the commands above to create the “Hello World” graph.

Note: There should not be an empty space between the function name and (; otherwise, this results in an error.

Terminal 1
Terminal
Loading...