Perform Graph Queries

Shortest Path

Shortest path between an object a and an object b via a predicate p can achieved with the use of a path query.
This example uses the DBPedia database which can be cloned from TerminusHub. It gives the shortest path between band members of Whitesnake, bands that these members have been in, the members of these bands, the bands that these members have been in, etc. until finally we arrive at a band which plays Country music (a 6 hop path).
In Python:
1
#!/usr/bin/python3
2
3
import os
4
import time
5
import datetime
6
from terminusdb_client import WOQLClient
7
from terminusdb_client import WOQLQuery as WOQL
8
9
# Connect to the server
10
server_url = "http://127.0.0.1:6363"
11
db = "dbpedia_1"
12
user = "admin"
13
account = "admin"
14
key = "root"
15
client = WOQLClient(server_url)
16
client.connect(user=user, account=account, key=key, db=db)
17
18
query = WOQL().limit(1,
19
WOQL.woql_and(
20
WOQL().path("Whitesnake", "(bandMember>,<bandMember)+", "v:Band","v:Path"),
21
WOQL().triple("v:Band", "genre", "Country_music"),
22
))
23
result = client.query(query)
24
print(result['bindings'][0]['Band'])
25
print(result['bindings'][0]['Path'])
Copied!
The answer we obtain for the band is Angelfire_(band) with the path:
1
"Whitesnake" - "bandMember" -> "Reb_Beach"
2
"Winger_(band)" - "bandMember" -> "Reb_Beach"
3
"Winger_(band)" - "bandMember" -> "Rod_Morgenstein"
4
"Dixie_Dregs" - "bandMember" -> "Rod_Morgenstein"
5
"Dixie_Dregs" - "bandMember" -> "Steve_Morse"
6
"Angelfire_(band)"- "bandMember" -> "Steve_Morse"
Copied!
Copy link