/
neo4j_pathfinder.py
60 lines (53 loc) · 1.66 KB
/
neo4j_pathfinder.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
from neo4j import GraphDatabase
QUERIES = {
"dijkstra": """
MATCH (n:Intersection)
WHERE n.node_osm_id = $source_gid
MATCH (p:Intersection)
WHERE p.node_osm_id = $target_gid
CALL apoc.algo.dijkstra(n,p,'ROUTE','distance')
YIELD path AS j
RETURN j
""",
"astar": """
MATCH (n:Intersection)
WHERE n.node_osm_id = $source_gid
MATCH (p:Intersection)
WHERE p.node_osm_id = $target_gid
CALL apoc.algo.aStar(n,p,'ROUTE','distance','lat','lon')
YIELD path AS j
RETURN j
""",
}
class Neo4jPathFinder:
def __init__(
self,
host="localhost",
port="7687",
user="neo4j",
password="pass",
default_algorithm="dijkstra",
):
self.driver = GraphDatabase.driver(
"bolt://" + host + ":" + port, auth=(user, password)
)
self.default_algorithm = default_algorithm
def close(self):
self.driver.close()
def get_path(self, source_gid, target_gid, algorithm=None):
# print("Origen: " + str(source_gid) + "Objetivo: " + str(target_gid))
algorithm = algorithm if algorithm else self.default_algorithm
query = QUERIES[algorithm]
result = {}
with self.driver.session() as session:
with session.begin_transaction() as tx:
aux = tx.run(query, source_gid=source_gid, target_gid=target_gid)
for record in aux:
result = record.data()
# print(result)
return result
# TEST
if __name__ == "__main__":
greeter = Neo4jPathFinder()
coso = greeter.get_path(287752964, 259017838)
greeter.close()