1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ Created on Sat Apr 6 18:21:28 2024
4
+
5
+ See issue https://github.com/RDFLib/rdflib/issues/2957.
6
+
7
+ @author: Administrator
8
+ """
9
+ from rdflib import Graph , Literal , URIRef , Variable
10
+ import os
11
+
12
+ current_dir = os .getcwd ()
13
+
14
+ GraphString = '''
15
+
16
+ prefix ex: <https://www.example.org/>
17
+
18
+ ex:document ex:subject "Nice cars" .
19
+
20
+ ex:document ex:theme "Car" .
21
+
22
+ '''
23
+
24
+ someGraph = Graph ()
25
+
26
+ someGraph .parse (data = GraphString , format = "turtle" )
27
+
28
+ # This query states first a normal triple pattern and then an optional clause with a subselect query.
29
+ Query1 = someGraph .query ('''
30
+
31
+ prefix ex: <https://www.example.org/>
32
+
33
+ select ?subject ?theme
34
+
35
+ where {
36
+
37
+ ?doc1 ex:subject ?subject.
38
+
39
+ OPTIONAL
40
+ {
41
+ select ?theme
42
+ where {
43
+ ?doc1 ex:theme ?theme.
44
+ }
45
+ }
46
+ }
47
+ ''' )
48
+
49
+ filepath = current_dir + "/output1.txt"
50
+
51
+ # Print the results with variable names and their bindings
52
+ print ('\n Results for Query1: \n ' )
53
+ for row in Query1 :
54
+ print ("Result 'subject: " + str (row .subject ) + "'\n Result should show 'subject: Nice cars' \n " )
55
+ print ("Result 'theme: " + str (row .theme ) + "'\n Result should show 'theme: Car'" )
56
+
57
+ with open (filepath , 'w' , encoding = 'utf-8' ) as file :
58
+ file .write (str (row ))
59
+ # Result should yield two rows:
60
+ # subject: Nice cars
61
+ # theme: Car
62
+
63
+
64
+ # This query states first an optional clause with a subselect query and then a normal triple pattern.
65
+ Query2 = someGraph .query ('''
66
+
67
+ prefix ex: <https://www.example.org/>
68
+
69
+ select ?subject ?theme
70
+
71
+ where {
72
+
73
+ OPTIONAL
74
+ {
75
+ select ?theme
76
+ where {
77
+ ?doc1 ex:theme ?theme.
78
+ }
79
+ }
80
+ ?doc1 ex:subject ?subject.
81
+ }
82
+ ''' )
83
+
84
+ filepath = current_dir + "/output2.txt"
85
+
86
+ # Print the results with variable names and their bindings
87
+ print ('\n Results for Query2: \n ' )
88
+ for row in Query2 :
89
+ print ("Result 'subject: " + str (row .subject ) + "'\n Result should show 'subject: Nice cars' \n " )
90
+ print ("Result 'theme: " + str (row .theme ) + "'\n Result should show 'theme: Car'" )
91
+
92
+ with open (filepath , 'w' , encoding = 'utf-8' ) as file :
93
+ file .write (str (row ))
94
+
95
+ # Result should yield two rows:
96
+ # subject: Nice cars
97
+ # theme: Car
0 commit comments