SQL, directed graph, finding node(s) with given properties

Status
Not open for further replies.

puffinus

Ars Praefectus
4,381
Subscriptor
I have a directed graph with nodes. Call it a graph of cities and roads connecting them. The cities are named in a mostly but not guaranteed-unique way. A road is identified by the city it departs from, the direction in which it leaves the city, and the destination city. The number of roads out of a given city is variable. The roads are directional: if two cities are connected in both directions, there are two roads (this being the usual case).

Restructuring the database is an option.

Presently,

a city has:
a unique integer ID (autoincrement, there's no significance to it)
a name (mostly but not entirely unique)

a road has:
a unique integer ID (autoincrement, there's no significance to it)
a from ID (refers to city)
a to ID (refers to city)


My problem:
I am given a node name and the list of paths applying to it. The paths are identified by direction and destination, not by id. Is there an efficient way in SQL to write a query for a list of cities matching that description?

I'm not experienced in SQL. Finding a collection of cities with the given name, processing the results in a procedural language, and then doing followup queries against those particular cities to see if the roads match is easy, but is there a reasonable way to do that in one step with SQL?
 

Richard Berg

Ars Legatus Legionis
43,037
Subscriptor
I don't quite understand the problem. What does it mean for a path to have direction + destination? The direction = "away" case seems clear enough, but if direction is "toward the given node" doesn't that force the destination to be said node, leaving the from_node unfixed?

Do you need to crawl paths of length > 1 or do you only care about direct connections (1 road = 2 cities = 2 joins)?

Note that transitive closure can't be expressed in standard SQL. Some vendors provide extensions (typical keyword: WITH RECURSIVE [...cte...] ).
 

metadaemon

Wise, Aged Ars Veteran
121
I think this will get you all your candidate matches in one shot. You would need to process each batch of records by city.id programatically to verify the roads match.

Code:
-- T-SQL - you might need to revise for you platform.
SELECT 'from' as [direction], city.name, road.id, city.id
  FROM road INNER JOIN city ON road.fromid = city.id
 WHERE city.name = 'something'
UNION ALL
SELECT 'to' as [direction], city.name, road.id, city.id
  FROM road INNER JOIN city ON road.toid = city.id
 WHERE city.name = 'something'
 ORDER BY city.id;

If the result returned is too big to process in the application, you would need to insert your search parameters into a temp table, do a join similar to the above and find the city.id from the result with the right number of paths.

This is a classic graph application. Have you considered a graph database? If you're looking at n-degree path calculations, SQL based products will not perform.
 

puffinus

Ars Praefectus
4,381
Subscriptor
[url=http:/civis/viewtopic.php?p=27230905#p27230905:2e9alpup said:
Richard Berg[/url]":2e9alpup]I don't quite understand the problem. What does it mean for a path to have direction + destination? The direction = "away" case seems clear enough, but if direction is "toward the given node" doesn't that force the destination to be said node, leaving the from_node unfixed?

You could as well call the direction an arbitrary label (Route 66). The key is that the label isn't the same from both ends: City "A" might be connected to City "B" by the path leaving city A with designation 2. That doesn't imply either that a route exists back from City "B" or that the designation will be 2 if such a route does exist.

As I said, I'm free to modify the database if that helps things (such as moving my direction to a separate label and providing a common identifier that would be guaranteed identical if this particular directed path has a reverse path).

Do you need to crawl paths of length > 1 or do you only care about direct connections (1 road = 2 cities = 2 joins)?

Direct connections. I recognize that trying to do arbitrary depths in SQL results in an increasingly contorted query for each additional step required. As a consequence, if I need to implement something like shortest path I'll load it up into a better data structure than a SQL database.

Note that transitive closure can't be expressed in standard SQL. Some vendors provide extensions (typical keyword: WITH RECURSIVE [...cte...] ).

I think I understand the words but I can't understand the meaning in the context of my problem. Small words please :) I may understand what it is but not the proper terminology to describe it.
 

puffinus

Ars Praefectus
4,381
Subscriptor
[url=http:/civis/viewtopic.php?p=27231003#p27231003:12b8nk23 said:
metadaemon[/url]":12b8nk23]I think this will get you all your candidate matches in one shot. You would need to process each batch of records by city.id programatically to verify the roads match.

Code:
-- T-SQL - you might need to revise for you platform.

Sqlite is the preferred solution for the database so that I can embed it. I could conceivably switch databases but if so I'd be weighing that against using Sqlite and doing temporary loads into some other storage for processing in C/C++.

The database will be relatively static and probably not over a GB so most of the queries could use optimizations such as running entirely in memory. It's fine if modifications to the database take time; queries should be relatively quick.

This is a classic graph application. Have you considered a graph database? If you're looking at n-degree path calculations, SQL based products will not perform.

It's tempting, but complicated things like path calcs would be relatively rare and most of the time I could run the important ones in advance such that time to execute isn't a problem unless it gets really absurd in realtime on good hardware.

I do recognize that SQL itself is not the place to do the really heavy lifting. I'm just trying to find out if I'm missing a relatively easy SQL solution because of my inexperience with the language.
 

ShuggyCoUk

Ars Legatus Legionis
10,387
Subscriptor++
How common are name collisions?

You only need this complex structure for the collisions, so just store the pre-computed collision set, by name, including the names of all roads involved for each one. That then becomes trivial to query (since it will be tiny if collisions are rare) and easily indexed by the name of the city node, then the road names, which is what you're querying from.
 

puffinus

Ars Praefectus
4,381
Subscriptor
[url=http:/civis/viewtopic.php?p=27234065#p27234065:3kd01hif said:
ShuggyCoUk[/url]":3kd01hif]How common are name collisions?

You only need this complex structure for the collisions, so just store the pre-computed collision set, by name, including the names of all roads involved for each one. That then becomes trivial to query (since it will be tiny if collisions are rare) and easily indexed by the name of the city node, then the road names, which is what you're querying from.

Seems practical. I wouldn't think collisions would be more than 1% (made up but small).
 

puffinus

Ars Praefectus
4,381
Subscriptor
Thanks everyone!

The solution that's working for me (hopefully without typos since it's transcribing from a slightly different db structure):

I'm dynamically generating the SQL so I can have an arbitrary number of INTERSECT clauses based on the number of roads leading out of a city. In the real application, it's using named parameters.

It's probably not very fast but in my case accepting that is worth it to avoid splitting up the business logic between multiple languages.

This example uses a city with two roads leading out.

SELECT o.city_id as cityid FROM city o WHERE o.cityname = [city name]

INTERSECT

SELECT o.city_id AS cityid FROM city o INNER JOIN road r ON o.city_id = road.from_id AND road.to_id = [destination 1]

INTERSECT

SELECT o.city_id AS cityid FROM city o INNER JOIN road r ON o.city_id = road.from_id AND road.to_id = [destination 2]

INTERSECT

SELECT r.from_id AS cityid FROM road r
GROUP BY cityid
HAVING COUNT(*) = [2]
;


If desired I can add a check on road direction/route number (which I described in my text but omitted from the database description in the existing queries).


Edit: and I see that I can use DISTINCT and chain a variable number of OR's to reduce the path check to one query since I'm also doing a count.
 

puffinus

Ars Praefectus
4,381
Subscriptor
[url=http:/civis/viewtopic.php?p=27285899#p27285899:3q95alq9 said:
naschbac[/url]":3q95alq9]I'd advise not using a SQL database as a graph database. This is a terrible use case for SQL.

I would generally agree.

In this case I've got a few relatively minor graph functions to implement on a database which is mostly normal business-type data and logic.

Unless I see an unacceptable performance problem, it seems better to keep as much as I can in one database and search/query language rather than splitting the implementation up.
 
Status
Not open for further replies.