SQL and graphs
Ursa runs the SQL that Apache DataFusion runs: SELECT, joins, aggregates, window functions, CREATE VIEW, COPY … TO, EXPLAIN, SET and SHOW. To that it adds files as tables, and graphs: CREATE PROPERTY GRAPH to define one and GRAPH_TABLE to match patterns in it, both from SQL/PGQ, the property graph part of the SQL standard.
The examples on this page share one session. They start with two views over the karate club files (see Get started to download them):
CREATE VIEW members AS SELECT * FROM 'karate_nodes.csv';CREATE VIEW ties AS SELECT * FROM 'karate_edges.csv';CREATE PROPERTY GRAPH
Section titled “CREATE PROPERTY GRAPH”A graph is a name for an edge table, and optionally vertex tables. Algorithms, traversals and GRAPH_TABLE patterns then take the graph’s name:
CREATE PROPERTY GRAPH karate VERTEX TABLES (members KEY (id)) EDGE TABLES ( ties SOURCE KEY (src) REFERENCES members (id) DESTINATION KEY (dst) REFERENCES members (id) );- An edge table is any table or view. Each row is an edge from its
SOURCE KEYcolumn to itsDESTINATION KEYcolumn. The two columns must both be integers or both be strings. - A vertex table defines the nodes and gives them attributes, keyed by its
KEYcolumn. Every key is a node, one with no edges included. An edge whose source or destination is not a key, or is NULL, is left out of the graph. - A key identifies one row. A vertex table with a duplicate or NULL key is refused when a query reads it. Deduplicate it in a view first:
SELECT DISTINCT ON (id) * FROM people WHERE id IS NOT NULL ORDER BY id. - The vertex table is optional. Without one, the nodes are the endpoints of the edges:
CREATE PROPERTY GRAPH g EDGE TABLES (ties SOURCE KEY (src) DESTINATION KEY (dst)). - Labels and properties. Each table has a label, its name unless
LABELgives others, and its columns are properties unless aPROPERTIESclause says otherwise.
A graph with one edge table and at most one vertex table is a schema with two tables. karate.edges holds the edges, and karate.nodes one row per node, with the vertex table’s columns:
SELECT count(*) AS edges FROM karate.edges;┌───────┐│ edges ││ Int64 │├───────┤│ 78 │└───────┘A graph over a view that filters the edges is a subgraph. With a vertex table, its nodes are still every key; without one, they are the endpoints of the edges it keeps.
OR REPLACE replaces a graph of the same name, and IF NOT EXISTS does nothing if there is one. There is no ALTER PROPERTY GRAPH: write the new definition with CREATE OR REPLACE. DROP PROPERTY GRAPH karate drops a graph and leaves its tables alone.
Several tables
Section titled “Several tables”A graph can have any number of vertex and edge tables. Here members follow each other and write posts:
CREATE VIEW posts AS SELECT * FROM (VALUES (100, 'hello'), (101, 'graphs')) t(pid, title);CREATE VIEW wrote AS SELECT * FROM (VALUES (0, 100), (33, 101)) t(author, post);CREATE PROPERTY GRAPH club VERTEX TABLES ( members AS person LABEL person PROPERTIES (id, club), posts ) EDGE TABLES ( ties SOURCE KEY (src) REFERENCES person (id) DESTINATION KEY (dst) REFERENCES person (id) LABEL knows, wrote SOURCE KEY (author) REFERENCES person (id) DESTINATION KEY (post) REFERENCES posts (pid) );Neither vertex table names its KEY: each is the column the edges reference. An algorithm runs on one vertex table and one edge table, as in DuckPGQ, so name the pair after the graph: pagerank(club, person, knows).
SHOW GRAPHS and DESCRIBE GRAPH
Section titled “SHOW GRAPHS and DESCRIBE GRAPH”SHOW GRAPHS lists the graphs, one row per edge table, with its endpoint columns and whether the graph can be used. DESCRIBE GRAPH lists the columns of a graph’s tables, with each column’s role:
DESCRIBE GRAPH karate;┌────────────┬─────────────┬───────────┬─────────────┬──────────────┐│ table_name │ column_name │ data_type │ role │ origin ││ Utf8 │ Utf8 │ Utf8 │ Utf8 │ Utf8 │├────────────┼─────────────┼───────────┼─────────────┼──────────────┤│ nodes │ id │ Int64 │ node id │ members.id ││ nodes │ club │ Utf8 │ NULL │ members.club ││ edges │ src │ Int64 │ source │ ties.src ││ edges │ dst │ Int64 │ destination │ ties.dst │└────────────┴─────────────┴───────────┴─────────────┴──────────────┘Pattern matching
Section titled “Pattern matching”GRAPH_TABLE finds patterns of nodes and edges in a graph and returns them as a table. A pattern is nodes in parentheses and edges in brackets. COLUMNS says what each match returns:
SELECT *FROM GRAPH_TABLE (karate MATCH (a)-[e]-(b) WHERE a.club = 'Officer' AND b.club = 'Mr. Hi' COLUMNS (a.id AS officer, b.id AS member))ORDER BY officer, memberLIMIT 3;┌─────────┬────────┐│ officer │ member ││ Int64 │ Int64 │├─────────┼────────┤│ 9 │ 2 ││ 27 │ 2 ││ 28 │ 2 │└─────────┴────────┘These are friendships between the two clubs. -[e]- follows an edge either way; -[e]-> follows it only as stored, from a to b. a.club is a property of a: a column of its vertex table. The result is a table like any other: filter it, join it, aggregate it.
GRAPH_TABLE ( graph MATCH path [, path …] [WHERE condition] [COLUMNS ( expression [AS name], … ) | COLUMNS (*)] )
path := node (edge node)*node := ( [variable] [:label | IS label] [WHERE condition] )edge := -[ … ]-> | <-[ … ]- | -[ … ]-- Variables name what a node or edge binds to. A variable used twice is the same node:
MATCH (a)-[]->(b)-[]->(c), (a)-[]->(c)finds triangles. - Labels say which tables a variable reads:
(p:person)or(p IS person).(p:person|school)reads either. - Conditions go inside a node or edge,
(a WHERE a.id = 0), or after the pattern, where they can use every variable. COLUMNSleft out, orCOLUMNS (*), returns every property of each variable, as DuckPGQ does.
A GRAPH_TABLE joins to an algorithm like any table. The most central members tied to member 33:
SELECT id, round(pagerank, 4) AS pagerankFROM GRAPH_TABLE (karate MATCH (a WHERE a.id = 33)-[]-(b) COLUMNS (b.id AS id))JOIN pagerank(karate, direction => 'both') USING (id)ORDER BY pagerank DESCLIMIT 3;┌───────┬──────────┐│ id │ pagerank ││ Int64 │ Float64 │├───────┼──────────┤│ 32 │ 0.0717 ││ 31 │ 0.0372 ││ 23 │ 0.0315 │└───────┴──────────┘Paths of any length
Section titled “Paths of any length”A quantifier after an edge repeats it: -[e]->{1,3} is one to three edges, * any number, + one or more. MATCH p = … names the path, and path_length(p), vertices(p) and edges(p) describe it. How far member 16 is from member 26, and the way:
SELECT *FROM GRAPH_TABLE (karate MATCH p = ANY SHORTEST (a WHERE a.id = 16)-[e]-*(b WHERE b.id = 26) COLUMNS (path_length(p) AS steps, vertices(p) AS members));┌───────┬───────────────────────┐│ steps │ members ││ Int64 │ List(non-null Int64) │├───────┼───────────────────────┤│ 5 │ [16, 5, 0, 8, 33, 26] │└───────┴───────────────────────┘A selector, after p =, says which paths to keep for each first and last node:
| Selector | Keeps |
|---|---|
none, or ALL |
every path |
ANY SHORTEST |
one shortest path |
SHORTEST k |
the k shortest paths |
ALL SHORTEST |
every path as short as the shortest |
A path mode says what a path may repeat: WALK (the default) anything, TRAIL no edge, ACYCLIC no node, SIMPLE no node except where it started. Without a selector, a path of unbounded length needs one of the last three.
What is fast. A match is fast when it starts from a few nodes named by their key, as a.id = 16 does above, or a.id IN (0, 33). From such a node, Ursa follows the graph’s index outward one edge at a time instead of joining the whole edge table. A pattern with no bound node is planned as joins. Either way, the rows are the same.
Statements Ursa adds
Section titled “Statements Ursa adds”| Statement | What it does |
|---|---|
SELECT … FROM 'file.parquet', read_parquet, read_csv, read_json |
Read a file as a table (Files and storage) |
COPY … TO |
Write a query’s rows to a file (Files and storage) |
CREATE PROPERTY GRAPH, DROP PROPERTY GRAPH |
Define or drop a graph |
SHOW GRAPHS, DESCRIBE GRAPH |
List the graphs, or a graph’s columns |
GRAPH_TABLE |
Match patterns of nodes and edges |
ATTACH 'file.ursa' |
Open a database file in an in-memory session (the database file) |
SET, SHOW, RESET |
Change and read an ursa. setting, for the session |
The graph functions, such as pagerank(karate), are table functions: see Algorithms.
Coming from DuckDB
Section titled “Coming from DuckDB”Ursa’s SQL works like DuckDB’s in the ways you use most: you name a file in FROM, read_csv and friends take DuckDB’s options, and the shell takes the same flags and dot-commands. The engine underneath is DataFusion, though, so some things differ:
- Column names. An expression without an alias is named the way DataFusion writes it:
SELECT 42gives a column namedInt64(42). Name the columns you keep withAS. - Case. Unquoted names are folded to lower case, as in PostgreSQL.
- The catalog. The default catalog and schema are
datafusionandpublic, notmemoryandmain. - CSV and JSON. CSV files are read with a header line and a comma, unless
headerordelimsays otherwise. A.jsonfile is read as one object per line; for one JSON array, useread_json(path, format => 'array'). - Tables. A database file stores views and graphs, not rows, so
CREATE TABLE … ASis refused in a database session. In memory, it works.
Coming from SQL/PGQ or DuckPGQ
Section titled “Coming from SQL/PGQ or DuckPGQ”Most of what you write for SQL/PGQ or DuckPGQ runs in Ursa as it is. Ursa follows three rules:
- Where the standard says how, Ursa does it that way:
CREATE PROPERTY GRAPHandGRAPH_TABLE … MATCH. - Where the standard says nothing, Ursa does what DuckPGQ does. No standard defines graph algorithms, so Ursa takes DuckPGQ’s calls, such as
pagerank(pg, Student, know), and its names, such asweakly_connected_component. - Ursa’s own additions, such as named parameters (
damping => 0.9), are extensions. The standard form works beside each one.
The main differences: Ursa’s PageRank scores sum to 1, as NetworkX’s do, where DuckPGQ’s sum to a little less. Every Ursa edge is directed, so ~[e]~ is refused with a pointer to -[e]-. Keys of several columns, ONE ROW PER STEP and LATERAL GRAPH_TABLE are not supported yet, and each is refused with a message, never read as something else.