-
Notifications
You must be signed in to change notification settings - Fork 0
/
tutorial_examples_40.py
2401 lines (2205 loc) · 99.9 KB
/
tutorial_examples_40.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from franz.openrdf.sail.allegrographserver import AllegroGraphServer
from franz.openrdf.repository.repository import Repository
from franz.miniclient import repository
from franz.openrdf.query.query import QueryLanguage
from franz.openrdf.model import URI
from franz.openrdf.vocabulary.rdf import RDF
from franz.openrdf.vocabulary.rdfs import RDFS
from franz.openrdf.vocabulary.owl import OWL
from franz.openrdf.vocabulary.xmlschema import XMLSchema
from franz.openrdf.query.dataset import Dataset
from franz.openrdf.rio.rdfformat import RDFFormat
from franz.openrdf.rio.rdfwriter import NTriplesWriter
from franz.openrdf.rio.rdfxmlwriter import RDFXMLWriter
import os, urllib, datetime, time, sys
CURRENT_DIRECTORY = os.getcwd()
#AG_HOST = os.environ.get('AGRAPH_HOST', 'interconnectedhealth.org')
AG_HOST = os.environ.get('AGRAPH_HOST', '192.168.1.16')
AG_PORT = int(os.environ.get('AGRAPH_PORT', '10035'))
AG_CATALOG = os.environ.get('AGRAPH_CATALOG', 'system')
# AG_CATALOG = ''
AG_REPOSITORY = 'test'
AG_USER = 'testUser'
AG_PASSWORD = 'testUser'
# AG_USER = 'anonymous'
# AG_PASSWORD = ''
# Updated July 23, 2010 AG 4.1 BDC
RAISE_EXCEPTION_ON_VERIFY_FAILURE = False
def verify(expressionValue, targetValue, quotedExpression, testNum):
"""
Verify that 'expressionValue' equals 'targetValue'. If not,
raise an exception, or print a message advertising the failure.
"""
if not expressionValue == targetValue:
message = ("Diagnostic failure in example %s. Expression '%s' returns '%s' where '%s' expected." %
(testNum, quotedExpression, expressionValue, targetValue))
if RAISE_EXCEPTION_ON_VERIFY_FAILURE:
raise Exception(message)
else:
print "BWEEP BWEEP BWEEP BWEEP BWEEP BWEEP BWEEP BWEEP BWEEP BWEEP BWEEP BWEEP BWEEP BWEEP BWEEP \n ", message
def example0():
"""
Can we connect to AG?
"""
print ("Starting example example0().")
print "Current working directory is '%s'" % (os.getcwd())
server = AllegroGraphServer(AG_HOST, AG_PORT, AG_USER, AG_PASSWORD)
print "Available catalogs", server.listCatalogs()
def example1(accessMode=Repository.RENEW):
"""
Tests getting the repository up. Is called by the other examples to do the startup.
"""
print "Starting example1()."
print "Default working directory is '%s'" % (CURRENT_DIRECTORY)
server = AllegroGraphServer(AG_HOST, AG_PORT, AG_USER, AG_PASSWORD)
print "Available catalogs", server.listCatalogs()
## catalog = server.openCatalog(AG_CATALOG) ## named catalog
catalog = server.openCatalog() ## default rootCatalog
print "Available repositories in catalog '%s': %s" % (catalog.getName(), catalog.listRepositories())
myRepository = catalog.getRepository(AG_REPOSITORY, accessMode)
myRepository.initialize()
conn = myRepository.getConnection()
print "Repository %s is up! It contains %i statements." % (
myRepository.getDatabaseName(), conn.size())
indices = conn.listValidIndices()
print "All valid triple indices: %s" % (indices)
indices = conn.listIndices()
print "Current triple indices: %s" % (indices)
print "Removing graph indices..."
conn.dropIndex("gospi")
conn.dropIndex("gposi")
conn.dropIndex("gspoi")
indices = conn.listIndices()
print "Current triple indices: %s" % (indices)
print "Adding one graph index back in..."
conn.addIndex("gspoi")
indices = conn.listIndices()
print "Current triple indices: %s" % (indices)
return conn
def example2():
conn = example1()
print "Starting example2()."
print "Default working directory is '%s'" % (CURRENT_DIRECTORY)
## create some resources and literals to make statements out of
alice = conn.createURI("http://example.org/people/alice")
bob = conn.createURI("http://example.org/people/bob")
name = conn.createURI("http://example.org/ontology/name")
person = conn.createURI("http://example.org/ontology/Person")
bobsName = conn.createLiteral("Bob")
alicesName = conn.createLiteral("Alice")
print "Triple count before inserts: ", conn.size()
for s in conn.getStatements(None, None, None, None, False): print s
## alice is a person
conn.add(alice, RDF.TYPE, person)
## alice's name is "Alice"
conn.add(alice, name, alicesName)
## bob is a person
conn.add(bob, RDF.TYPE, person)
## bob's name is "Bob":
conn.add(bob, name, bobsName)
print "Added four triples."
print "Triple count: ", conn.size()
for s in conn.getStatements(None, None, None, None, False): print s
conn.remove(bob, name, bobsName)
print "Removed one triple."
print "Triple count: ", conn.size()
conn.add(bob, name, bobsName)
return conn
def example3():
conn = example2()
print "Starting example3()."
print "Default working directory is '%s'" % (CURRENT_DIRECTORY)
print "SPARQL query for all triples in repository."
try:
queryString = "SELECT ?s ?p ?o WHERE {?s ?p ?o .}"
tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString)
result = tupleQuery.evaluate();
try:
for bindingSet in result:
s = bindingSet.getValue("s")
p = bindingSet.getValue("p")
o = bindingSet.getValue("o")
print "%s %s %s" % (s, p, o)
finally:
result.close();
finally:
conn.close();
myRepository = conn.repository
myRepository.shutDown()
def example4():
conn = example2()
print "Starting example4()."
print "Default working directory is '%s'" % (CURRENT_DIRECTORY)
alice = conn.createURI("http://example.org/people/alice")
print "Searching for Alice using getStatements():"
statements = conn.getStatements(alice, None, None, False)
# statements.enableDuplicateFilter() ## there are no duplicates, but this exercises the code that checks
for s in statements:
print s
statements.close()
conn.close()
myRepository = conn.repository
myRepository.shutDown()
def example5():
"""
Typed Literals
"""
print "\nStarting example5()."
print "Default working directory is '%s'" % (CURRENT_DIRECTORY)
conn = example1()
conn.clear()
exns = "http://people/"
alice = conn.createURI("http://people/alice")
bob = conn.createURI(namespace=exns, localname="bob")
carol = conn.createURI(namespace=exns, localname="carol")
dave = conn.createURI(namespace=exns, localname="dave")
eric = conn.createURI(namespace=exns, localname="eric")
fred = conn.createURI(namespace=exns, localname="fred")
greg = conn.createURI(namespace=exns, localname="greg")
# numeric datatypes
age = conn.createURI(namespace=exns, localname="age")
fortyTwo = conn.createLiteral(42) # creates long
fortyTwoDouble = conn.createLiteral(42.0) # creates double
fortyTwoInt = conn.createLiteral('42', datatype=XMLSchema.INT)
fortyTwoLong = conn.createLiteral('42', datatype=XMLSchema.LONG)
fortyTwoFloat = conn.createLiteral('42', datatype=XMLSchema.FLOAT)
fortyTwoString = conn.createLiteral('42', datatype=XMLSchema.STRING)
fortyTwoPlain = conn.createLiteral('42') # creates untyped string
stmt1 = conn.createStatement(alice, age, fortyTwo)
stmt2 = conn.createStatement(bob, age, fortyTwoDouble)
stmt3 = conn.createStatement(carol, age, fortyTwoInt)
stmt4 = conn.createStatement(dave, age, fortyTwoLong)
stmt5 = conn.createStatement(eric, age, fortyTwoFloat)
stmt6 = conn.createStatement(fred, age, fortyTwoString)
stmt7 = conn.createStatement(greg, age, fortyTwoPlain)
conn.add(stmt1)
conn.add(stmt2)
conn.add(stmt3)
conn.addStatement(stmt4)
conn.addStatement(stmt5)
conn.addStatement(stmt6)
conn.addStatement(stmt7)
# This section retrieves the age triples to see what datatypes are present.
print "\nShowing all age triples using getStatements(). Seven matches."
statements = conn.getStatements(None, age, None)
for s in statements:
print s
print "----------------------------------------------------------------------------"
print "GARY: The SQARQL 'direct' matches in the following set of six examples produce no results."
# Matches against 42, undeclared int.
print "\ngetStatements() request for 42, matches longs."
statements = conn.getStatements(None, age, 42)
for s in statements:
print s
print "\nSPARQL matches for 42 (filter match) finds multiple numeric types."
queryString = """SELECT ?s ?p ?o WHERE {?s ?p ?o . filter (?o = 42)}"""
tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString)
result = tupleQuery.evaluate();
for bindingSet in result:
s = bindingSet[0]
p = bindingSet[1]
o = bindingSet[2]
print "%s %s %s" % (s, p, o)
print "\nSPARQL matches for 42 (direct match)."
queryString = """SELECT ?s ?p WHERE {?s ?p 42 .}"""
tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString)
result = tupleQuery.evaluate();
for bindingSet in result:
s = bindingSet[0]
p = bindingSet[1]
print "%s %s" % (s, p)
# Matches against 42.0, undeclared double.
print "\ngetStatements() request for 42.0 matches double but not float."
# statements = conn.getStatements(None, age, fortyTwoDouble)
statements = conn.getStatements(None, age, 42.0)
for s in statements:
print s
# Matches against fortyTwoDouble, Literal double.
print "\ngetStatements() request for fortyTwoDouble matches double but not float."
statements = conn.getStatements(None, age, fortyTwoDouble)
# statements = conn.getStatements(None, age, 42.0)
for s in statements:
print s
print "\nSPARQL matches for 42.0 (filter match) finds multiple numeric types."
queryString = """SELECT ?s ?p ?o WHERE {?s ?p ?o . filter (?o = 42.0)}"""
tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString)
result = tupleQuery.evaluate();
for bindingSet in result:
s = bindingSet[0]
p = bindingSet[1]
o = bindingSet[2]
print "%s %s %s" % (s, p, o)
print "\nSPARQL matches for 42.0 (direct match)."
queryString = """SELECT ?s ?p WHERE {?s ?p 42.0 .}"""
tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString)
result = tupleQuery.evaluate();
for bindingSet in result:
s = bindingSet[0]
p = bindingSet[1]
print "%s %s" % (s, p)
print "----------------------------------------------------------------------------"
# Matches against ints.
print "\ngetStatements() request for fortyTwoInt: %s" % (fortyTwoInt)
statements = conn.getStatements(None, age, fortyTwoInt)
# statements = conn.getStatements(None, age, "42"^^<http://www.w3.org/2001/XMLSchema#int>)
for s in statements:
print s
print "\nSPARQL matches for \"42\"^^<http://www.w3.org/2001/XMLSchema#int> (filter match) finds multple types."
queryString = """SELECT ?s ?p ?o WHERE {?s ?p ?o . filter (?o = "42"^^<http://www.w3.org/2001/XMLSchema#int>)}"""
tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString)
result = tupleQuery.evaluate();
for bindingSet in result:
s = bindingSet[0]
p = bindingSet[1]
o = bindingSet[2]
print "%s %s %s" % (s, p, o)
print "\nSPARQL matches for \"42\"^^<http://www.w3.org/2001/XMLSchema#int> (direct match) finds ints."
queryString = """SELECT ?s ?p WHERE {?s ?p "42"^^<http://www.w3.org/2001/XMLSchema#int>}"""
tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString)
result = tupleQuery.evaluate();
for bindingSet in result:
s = bindingSet[0]
p = bindingSet[1]
print "%s %s" % (s, p)
print "----------------------------------------------------------------------------"
# Matches against longs.
print "\ngetStatements() request for FortyTwoLong: %s" % (fortyTwoLong)
statements = conn.getStatements(None, age, fortyTwoLong)
for s in statements:
print s
print "\nSPARQL matches for \"42\"^^<http://www.w3.org/2001/XMLSchema#long> (filter match) finds multiple types."
queryString = """SELECT ?s ?p ?o WHERE {?s ?p ?o . filter (?o = "42"^^<http://www.w3.org/2001/XMLSchema#long>)}"""
tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString)
result = tupleQuery.evaluate();
for bindingSet in result:
s = bindingSet[0]
p = bindingSet[1]
o = bindingSet[2]
print "%s %s %s" % (s, p, o)
print "\nSPARQL matches for \"42\"^^<http://www.w3.org/2001/XMLSchema#long> (direct match) finds longs."
queryString = """SELECT ?s ?p WHERE {?s ?p "42"^^<http://www.w3.org/2001/XMLSchema#long>}"""
tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString)
result = tupleQuery.evaluate();
for bindingSet in result:
s = bindingSet[0]
p = bindingSet[1]
print "%s %s" % (s, p)
print "----------------------------------------------------------------------------"
# Matches against doubles.
print "\ngetStatements() request for fortyTwoDouble: %s finds a double." % (fortyTwoDouble)
statements = conn.getStatements(None, age, fortyTwoDouble)
for s in statements:
print s
print "\nSPARQL matches for \"42\"^^<http://www.w3.org/2001/XMLSchema#double> (filter match) finds multiple types."
queryString = """SELECT ?s ?p ?o WHERE {?s ?p ?o . filter (?o = "42"^^<http://www.w3.org/2001/XMLSchema#double>)}"""
tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString)
result = tupleQuery.evaluate();
for bindingSet in result:
s = bindingSet[0]
p = bindingSet[1]
o = bindingSet[2]
print "%s %s %s" % (s, p, o)
print "\nSPARQL matches for \"42\"^^<http://www.w3.org/2001/XMLSchema#double> (direct match) finds a double."
queryString = """SELECT ?s ?p WHERE {?s ?p "42"^^<http://www.w3.org/2001/XMLSchema#double>}"""
tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString)
result = tupleQuery.evaluate();
for bindingSet in result:
s = bindingSet[0]
p = bindingSet[1]
print "%s %s" % (s, p)
print "----------------------------------------------------------------------------"
# Matches against declared strings.
print "\ngetStatements() request for FortyTwoString: %s finds a string." % (fortyTwoString)
statements = conn.getStatements(None, age, fortyTwoString)
for s in statements:
print s
print "\nSPARQL matches for \"42\"^^<http://www.w3.org/2001/XMLSchema#string> (filter match)."
queryString = """SELECT ?s ?p ?o WHERE {?s ?p ?o . filter (?o = "42"^^<http://www.w3.org/2001/XMLSchema#string>)}"""
tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString)
result = tupleQuery.evaluate();
for bindingSet in result:
s = bindingSet[0]
p = bindingSet[1]
o = bindingSet[2]
print "%s %s %s" % (s, p, o)
print "\nSPARQL matches for \"42\"^^<http://www.w3.org/2001/XMLSchema#string> (direct match)."
queryString = """SELECT ?s ?p WHERE {?s ?p "42"^^<http://www.w3.org/2001/XMLSchema#string>}"""
tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString)
result = tupleQuery.evaluate();
for bindingSet in result:
s = bindingSet[0]
p = bindingSet[1]
print "%s %s" % (s, p)
print "----------------------------------------------------------------------------"
# Matches against plain literals.
print "\ngetStatements() triples that match plain literal \"42\"."
statements = conn.getStatements(None, age, "42")
for s in statements:
print s
print "\nSPARQL matches for plain literal \"42\" (filter match) finds a string."
queryString = """SELECT ?s ?p ?o WHERE {?s ?p ?o . filter (?o = "42")}"""
tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString)
result = tupleQuery.evaluate();
for bindingSet in result:
s = bindingSet[0]
p = bindingSet[1]
o = bindingSet[2]
print "%s %s %s" % (s, p, o)
print "\nSPARQL matches for plain literal \"42\" (direct match) finds a string."
queryString = """SELECT ?s ?p WHERE {?s ?p "42"}"""
tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString)
result = tupleQuery.evaluate();
for bindingSet in result:
s = bindingSet[0]
p = bindingSet[1]
print "%s %s" % (s, p)
print "----------------------------------------------------------------------------"
# Let's examine some string matching.
print "\nTests of string matching..."
favoriteColor = conn.createURI(namespace=exns, localname="favoriteColor")
UCred = conn.createLiteral('Red', datatype=XMLSchema.STRING)
LCred = conn.createLiteral('red', datatype=XMLSchema.STRING)
RedPlain = conn.createLiteral('Red') #plain literal
rouge = conn.createLiteral('rouge', datatype=XMLSchema.STRING)
Rouge = conn.createLiteral('Rouge', datatype=XMLSchema.STRING)
RougePlain = conn.createLiteral('Rouge') #plain literal
FrRouge = conn.createLiteral('Rouge', language="fr") #plain literal with language tag
conn.addTriples([(alice, favoriteColor, UCred),
(bob, favoriteColor, LCred),
(carol, favoriteColor, RedPlain),
(dave, favoriteColor, rouge),
(eric, favoriteColor, Rouge),
(fred, favoriteColor, RougePlain),
(greg, favoriteColor, FrRouge)])
print "\nShowing all color triples using getStatements(). Should be seven."
statements = conn.getStatements(None, favoriteColor, None)
for s in statements:
print s
# Explore matching on these strings.
# Matches against undeclared strings. These are capitalized Red.
print "\ngetStatements() triples that match \"Red\". Finds exact match. "
statements = conn.getStatements(None, favoriteColor, "Red")
for s in statements:
print s
print "\nSPARQL matches for \"Red\" (filter match) find exact match."
queryString = """SELECT ?s ?p ?o WHERE {?s ?p ?o . filter (?o = "Red")}"""
tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString)
result = tupleQuery.evaluate();
for bindingSet in result:
s = bindingSet[0]
p = bindingSet[1]
o = bindingSet[2]
print "%s %s %s" % (s, p, o)
print "\nSPARQL matches for \"Red\" (direct match) finds exact match."
queryString = """SELECT ?s ?p WHERE {?s ?p "Red"}"""
tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString)
result = tupleQuery.evaluate();
for bindingSet in result:
s = bindingSet[0]
p = bindingSet[1]
print "%s %s" % (s, p)
print "----------------------------------------------------------------------------"
# Matches against undeclared strings. These are capital Rouge.
print "\ngetStatements() triples that match \"Rouge\". Finds exact match. "
statements = conn.getStatements(None, favoriteColor, "Rouge")
for s in statements:
print s
print "\nSPARQL matches for \"Rouge\" (filter match) find string and plain."
queryString = """SELECT ?s ?p ?o WHERE {?s ?p ?o . filter (?o = "Rouge")}"""
tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString)
result = tupleQuery.evaluate();
for bindingSet in result:
s = bindingSet[0]
p = bindingSet[1]
o = bindingSet[2]
print "%s %s %s" % (s, p, o)
print "\nSPARQL matches for \"Rouge\" (direct match) finds string and plain."
queryString = """SELECT ?s ?p WHERE {?s ?p "Rouge"}"""
tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString)
result = tupleQuery.evaluate();
for bindingSet in result:
s = bindingSet[0]
p = bindingSet[1]
print "%s %s" % (s, p)
print "----------------------------------------------------------------------------"
# Matches against undeclared strings. These are capital Rouge in French.
print "\ngetStatements() triples that match \"Rouge\"@fr. Finds exact match. "
statements = conn.getStatements(None, favoriteColor, FrRouge)
for s in statements:
print s
print "\nSPARQL matches for \"Rouge\"@fr (filter match) find exact match."
queryString = """SELECT ?s ?p ?o WHERE {?s ?p ?o . filter (?o = "Rouge"@fr)}"""
tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString)
result = tupleQuery.evaluate();
for bindingSet in result:
s = bindingSet[0]
p = bindingSet[1]
o = bindingSet[2]
print "%s %s %s" % (s, p, o)
print "\nSPARQL matches for \"Rouge\"@fr (direct match) finds exact match."
queryString = """SELECT ?s ?p WHERE {?s ?p "Rouge"@fr}"""
tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString)
result = tupleQuery.evaluate();
for bindingSet in result:
s = bindingSet[0]
p = bindingSet[1]
print "%s %s" % (s, p)
print "----------------------------------------------------------------------"
print "\nSPARQL matches for (fn:lower-case(str(?o)) = \"rouge\") (filter match) finds four."
queryString = """PREFIX fn: <http://www.w3.org/2005/xpath-functions#> SELECT ?s ?p ?o WHERE {?s ?p ?o . filter (fn:lower-case(str(?o)) = "rouge")}"""
tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString)
result = tupleQuery.evaluate();
for bindingSet in result:
s = bindingSet[0]
p = bindingSet[1]
o = bindingSet[2]
print "%s %s %s" % (s, p, o)
print "----------------------------------------------------------------------------"
# Let's try some Booleans. A person is, or is not, a "senior."
senior = conn.createURI(namespace=exns, localname="seniorp")
# The values True and False are predefined.
print "True = %s" % True # These work.
print "False = %s" % False
# print "true = %s" % true # These don't work.
# print "false = %s" % false
trueValue = conn.createLiteral("true", datatype=XMLSchema.BOOLEAN)
falseValue = conn.createLiteral("false", datatype=XMLSchema.BOOLEAN)
conn.addTriple(alice, senior, trueValue)
conn.addTriple(bob, senior, falseValue)
# Let's look at the new triples.
print "\ngetStatements() all senior triples, should be two. "
statements = conn.getStatements(None, senior, None)
for s in statements:
print s
# Try matches for Boolean "True".
print "\ngetStatements() triples that match Boolean True. No matches."
statements = conn.getStatements(None, senior, True) # no matches
for s in statements:
print s
print "----------------------------------------------------------------------------"
print "\ngetStatements() triples that match trueValue. One match."
statements = conn.getStatements(None, senior, trueValue)
for s in statements:
print s
print "\nSPARQL matches for true (filter match). One match."
queryString = """SELECT ?s ?p ?o WHERE {?s ?p ?o . filter (?o = true)}"""
tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString)
result = tupleQuery.evaluate();
for bindingSet in result:
s = bindingSet[0]
p = bindingSet[1]
o = bindingSet[2]
print "%s %s %s" % (s, p, o)
print "\nSPARQL matches for true (direct match). One match."
queryString = """SELECT ?s ?p WHERE {?s ?p true}"""
tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString)
result = tupleQuery.evaluate();
for bindingSet in result:
s = bindingSet[0]
p = bindingSet[1]
print "%s %s" % (s, p)
print "\nSPARQL matches for \"true\"^^<http://www.w3.org/2001/XMLSchema#boolean> (filter match). One match."
queryString = """SELECT ?s ?p ?o WHERE {?s ?p ?o . filter (?o = "true"^^<http://www.w3.org/2001/XMLSchema#boolean>)}"""
tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString)
result = tupleQuery.evaluate();
for bindingSet in result:
s = bindingSet[0]
p = bindingSet[1]
o = bindingSet[2]
print "%s %s %s" % (s, p, o)
print "\nSPARQL matches for \"true\"^^<http://www.w3.org/2001/XMLSchema#boolean> (direct match). One match."
queryString = """SELECT ?s ?p WHERE {?s ?p "true"^^<http://www.w3.org/2001/XMLSchema#boolean>}"""
tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString)
result = tupleQuery.evaluate();
for bindingSet in result:
s = bindingSet[0]
p = bindingSet[1]
print "%s %s" % (s, p)
print "-----------------------------------------------------------------------------------"
# Dates, times, and datetimes
birthdate = conn.createURI(namespace=exns, localname="birthdate")
date = conn.createLiteral('1984-12-06', datatype=XMLSchema.DATE)
datetime = conn.createLiteral('1984-12-06T09:00:00', datatype=XMLSchema.DATETIME)
time = conn.createLiteral('09:00:00Z', datatype=XMLSchema.TIME)
datetimeOffset = conn.createLiteral('1984-12-06T09:00:00+01:00', datatype=XMLSchema.DATETIME)
print "Printing out Literals for date, datetime, time, and datetime with Zulu offset."
print date
print datetime
print time
print datetimeOffset
conn.addTriples([(alice, birthdate, date),
(bob, birthdate, datetime),
(carol, birthdate, time),
(dave, birthdate, datetimeOffset)])
print "\nShowing all birthday triples using getStatements(). Should be four."
statements = conn.getStatements(None, birthdate, None)
for s in statements:
print s
print "----------------------------------------------------------------------------"
print "\ngetStatements() triples that match date: %s One match." % (date)
statements = conn.getStatements(None, birthdate, date)
for s in statements:
print s
print "\nSPARQL matches for \'1984-12-06\'^^<http://www.w3.org/2001/XMLSchema#date> (filter match) finds one."
queryString = """SELECT ?s ?p ?o WHERE {?s ?p ?o . filter (?o = '1984-12-06'^^<http://www.w3.org/2001/XMLSchema#date>)}"""
tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString)
result = tupleQuery.evaluate();
for bindingSet in result:
s = bindingSet[0]
p = bindingSet[1]
o = bindingSet[2]
print "%s %s %s" % (s, p, o)
print "\nSPARQL matches for \'1984-12-06\'^^<http://www.w3.org/2001/XMLSchema#date> (direct match) finds one."
queryString = """SELECT ?s ?p WHERE {?s ?p '1984-12-06'^^<http://www.w3.org/2001/XMLSchema#date> .}"""
tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString)
result = tupleQuery.evaluate();
for bindingSet in result:
s = bindingSet[0]
p = bindingSet[1]
print "%s %s" % (s, p)
print "----------------------------------------------------------------------------"
print "\ngetStatements() triples that match datetime: %s One match." % (datetime)
statements = conn.getStatements(None, birthdate, datetime)
for s in statements:
print s
print "\nSPARQL matches for \"1984-12-06T09:00:00Z\"^^<http://www.w3.org/2001/XMLSchema#dateTime> (filter match) finds one."
queryString = """SELECT ?s ?p ?o WHERE {?s ?p ?o . filter (?o = '1984-12-06T09:00:00Z'^^<http://www.w3.org/2001/XMLSchema#dateTime>)}"""
tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString)
result = tupleQuery.evaluate();
for bindingSet in result:
s = bindingSet[0]
p = bindingSet[1]
o = bindingSet[2]
print "%s %s %s" % (s, p, o)
print "\nSPARQL matches for \'1984-12-06T09:00:00Z\'^^<http://www.w3.org/2001/XMLSchema#dateTime> (direct match) finds one."
queryString = """SELECT ?s ?p WHERE {?s ?p '1984-12-06T09:00:00Z'^^<http://www.w3.org/2001/XMLSchema#dateTime> .}"""
tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString)
result = tupleQuery.evaluate();
for bindingSet in result:
s = bindingSet[0]
p = bindingSet[1]
print "%s %s" % (s, p)
print "----------------------------------------------------------------------------"
print "\ngetStatements() triples that match time: %s One match." % (time)
statements = conn.getStatements(None, birthdate, time)
for s in statements:
print s
print "\nSPARQL matches for \"09:00:00Z\"^^<http://www.w3.org/2001/XMLSchema#time> (filter match) finds one."
queryString = """SELECT ?s ?p ?o WHERE {?s ?p ?o . filter (?o = "09:00:00Z"^^<http://www.w3.org/2001/XMLSchema#time>)}"""
tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString)
result = tupleQuery.evaluate();
for bindingSet in result:
s = bindingSet[0]
p = bindingSet[1]
o = bindingSet[2]
print "%s %s %s" % (s, p, o)
print "\nSPARQL matches for \"09:00:00Z\"^^<http://www.w3.org/2001/XMLSchema#time (direct match) finds one."
queryString = """SELECT ?s ?p WHERE {?s ?p "09:00:00Z"^^<http://www.w3.org/2001/XMLSchema#time> .}"""
tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString)
result = tupleQuery.evaluate();
for bindingSet in result:
s = bindingSet[0]
p = bindingSet[1]
print "%s %s" % (s, p)
print "----------------------------------------------------------------------------"
print "\ngetStatements() triples that match datetimeOffset: %s One match." % (datetimeOffset)
statements = conn.getStatements(None, birthdate, datetimeOffset)
for s in statements:
print s
print "\nSPARQL matches for \"1984-12-06T09:00:00+01:00\"^^<http://www.w3.org/2001/XMLSchema#dateTime> (filter match) finds one."
queryString = """SELECT ?s ?p ?o WHERE {?s ?p ?o . filter (?o = "1984-12-06T09:00:00+01:00"^^<http://www.w3.org/2001/XMLSchema#dateTime>)}"""
tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString)
result = tupleQuery.evaluate();
for bindingSet in result:
s = bindingSet[0]
p = bindingSet[1]
o = bindingSet[2]
print "%s %s %s" % (s, p, o)
print "\nSPARQL matches for \"1984-12-06T09:00:00+01:00\"^^<http://www.w3.org/2001/XMLSchema#dateTime> (direct match) finds one."
queryString = """SELECT ?s ?p WHERE {?s ?p "1984-12-06T09:00:00+01:00"^^<http://www.w3.org/2001/XMLSchema#dateTime> .}"""
tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString)
result = tupleQuery.evaluate();
for bindingSet in result:
s = bindingSet[0]
p = bindingSet[1]
print "%s %s" % (s, p)
conn.close();
myRepository = conn.repository
myRepository.shutDown()
def example6(close=True):
print "Starting example6()."
server = AllegroGraphServer(AG_HOST, AG_PORT, AG_USER, AG_PASSWORD)
catalog = server.openCatalog(AG_CATALOG)
myRepository = catalog.getRepository(AG_REPOSITORY, Repository.RENEW)
myRepository.initialize()
conn = myRepository.getConnection()
conn.clear()
conn.openSession() # open dedicated session to support Prolog queries in example17/18
# The following paths are relative to os.getcwd(), the working directory.
print "Default working directory is '%s'" % (CURRENT_DIRECTORY)
# If you get a "file not found" error, use os.chdir("your directory path") to
# point to the location of the data files. For AG Free Edition on Windows:
#os.chdir("C:\Program Files\AllegroGraphFJE32\python")
print "Current working directory is '%s'" % (os.getcwd())
path1 = "./python-vcards.rdf"
path2 = "./python-kennedy.ntriples"
context = conn.createURI("http://example.org#vcards")
conn.setNamespace("vcd", "http://www.w3.org/2001/vcard-rdf/3.0#");
## read kennedy triples into the null context:
print "Load python-kennedy.ntriples."
conn.add(path2, base=None, format=RDFFormat.NTRIPLES, contexts=None)
## read vcards triples into the context 'context':
print "Load vcards triples."
conn.addFile(path1, None, format=RDFFormat.RDFXML, context=context);
print "After loading, repository contains %i vcard triples in context '%s'\n and %i kennedy triples in context '%s'." % (
conn.size(context), context, conn.size('null'), 'null')
if close:
conn.closeSession()
else:
return conn # to chain to other examples
def example7():
conn = example6(False)
print "Starting example7()."
print "Match all and print subjects and contexts"
result = conn.getStatements(None, None, None, None, limit=25)
for row in result: print row.getSubject(), row.getContext()
print "\nSame thing with SPARQL query (can't retrieve triples in the null context)"
queryString = "SELECT DISTINCT ?s ?c WHERE {graph ?c {?s ?p ?o .} }"
tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString)
result = tupleQuery.evaluate();
for i, bindingSet in enumerate(result):
print bindingSet[0], bindingSet[1]
conn.closeSession()
conn.close();
myRepository = conn.repository
myRepository.shutDown()
import urlparse
def example8():
conn = example6(False)
print "Starting example8()."
context = conn.createURI("http://example.org#vcards")
outputFile = "/tmp/temp.nt"
#outputFile = None
if outputFile == None:
print "Writing RDF to Standard Out instead of to a file"
ntriplesWriter = NTriplesWriter(outputFile)
conn.export(ntriplesWriter, context); # Export vcards to .nt file.
outputFile2 = "/tmp/temp.rdf"
#outputFile2 = None
if outputFile2 == None:
print "Writing NTriples to Standard Out instead of to a file"
rdfxmlfWriter = RDFXMLWriter(outputFile2)
conn.export(rdfxmlfWriter, 'null') # Export kennedy triples to RDF/XML file
print "Exporting only the Family Name triples from vcards..."
familyName = conn.createURI("http://www.w3.org/2001/vcard-rdf/3.0#FN")
conn.exportStatements(None, familyName, None, False, RDFXMLWriter(None), context)
conn.closeSession()
conn.close();
myRepository = conn.repository
myRepository.shutDown()
def example9():
print "Starting example9()."
conn = example6(False)
conn.exportStatements(None, RDF.TYPE, None, False, RDFXMLWriter(None))
conn.closeSession()
print "About to close session in example 9:"
conn.close();
myRepository = conn.repository
myRepository.shutDown()
def example10():
"""
Datasets and multiple contexts
"""
print "Starting example10()."
conn = example1()
## Create URIs for resources, predicates and classes.
exns = "http://example.org/people/"
alice = conn.createURI(namespace=exns, localname="alice")
bob = conn.createURI(namespace=exns, localname="bob")
ted = conn.createURI(namespace=exns, localname="ted")
person = conn.createURI(namespace=exns, localname="Person")
name = conn.createURI(namespace=exns, localname="name")
## Create literal name values.
alicesName = conn.createLiteral("Alice")
bobsName = conn.createLiteral("Bob")
tedsName = conn.createLiteral("Ted")
## Create URIs to identify the named contexts.
context1 = conn.createURI(namespace=exns, localname="context1")
context2 = conn.createURI(namespace=exns, localname="context2")
## Assemble new statements and add them to the contexts.
conn.add(alice, RDF.TYPE, person, context1)
conn.add(alice, name, alicesName, context1)
conn.add(bob, RDF.TYPE, person, context2)
conn.add(bob, name, bobsName, context2)
conn.add(ted, RDF.TYPE, person) ## Added to null context
conn.add(ted, name, tedsName) ## Added to null context
## GetStatements() examples.
print "---------------------------------------------------------------"
statements = conn.getStatements(None, None, None)
print "All triples in all contexts: %s" % (conn.size())
for s in statements:
print s
print "---------------------------------------------------------------"
statements = conn.getStatements(None, None, None, ['null'])
print "All triples in null context: %s" % (conn.size(['null']))
for s in statements:
print s
print "---------------------------------------------------------------"
statements = conn.getStatements(None, None, None, [context1, context2])
print "Triples in contexts 1 or 2: %s" % (conn.size([context1, context2]))
for s in statements:
print s
print "---------------------------------------------------------------"
statements = conn.getStatements(None, None, None, ['null', context2])
print "Triples in contexts null or 2: %s" % (conn.size(['null', context2]))
for s in statements:
print s
## SPARQL examples, some using FROM and FROM NAMED
print "---------------------------------------------------------------"
queryString = """
SELECT ?s ?p ?o WHERE {?s ?p ?o . }
"""
tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString)
result = tupleQuery.evaluate();
print "No dataset restrictions."
for bindingSet in result:
print bindingSet.getRow()
print "---------------------------------------------------------------"
queryString = """
SELECT ?s ?p ?o ?c WHERE {GRAPH ?c {?s ?p ?o . }}
"""
tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString)
result = tupleQuery.evaluate()
print "No dataset. SPARQL graph query only."
for bindingSet in result:
print bindingSet.getRow()
print "---------------------------------------------------------------"
queryString = """
SELECT ?s ?p ?o FROM DEFAULT
WHERE {?s ?p ?o . }
"""
tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString)
result = tupleQuery.evaluate()
print queryString
for bindingSet in result:
print bindingSet.getRow()
print "---------------------------------------------------------------"
queryString = """
SELECT ?s ?p ?o FROM <http://example.org/people/context1>
WHERE {?s ?p ?o . }
"""
tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString)
result = tupleQuery.evaluate()
print queryString
for bindingSet in result:
print bindingSet.getRow()
print "---------------------------------------------------------------"
queryString = """
SELECT ?s ?p ?o FROM NAMED <http://example.org/people/context1>
WHERE {?s ?p ?o . }
"""
tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString)
result = tupleQuery.evaluate()
print queryString
for bindingSet in result:
print bindingSet.getRow()
print "---------------------------------------------------------------"
queryString = """
SELECT ?s ?p ?o ?g FROM NAMED <http://example.org/people/context1>
WHERE {GRAPH ?g {?s ?p ?o . }}
"""
tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString)
result = tupleQuery.evaluate()
print queryString
for bindingSet in result:
print bindingSet.getRow()
print "---------------------------------------------------------------"
queryString = """
SELECT ?s ?p ?o ?g
FROM DEFAULT
FROM <http://example.org/people/context1>
FROM NAMED <http://example.org/people/context2>
WHERE {{GRAPH ?g {?s ?p ?o . }} UNION {?s ?p ?o .}}
"""
## This query is the test case for bug19681
tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString)
result = tupleQuery.evaluate()
print queryString
for bindingSet in result:
print bindingSet.getRow()
## Dataset examples
print "---------------------------------------------------------------"
## testing default graph query:
queryString = """
SELECT ?s ?p ?o WHERE {?s ?p ?o . }
"""
ds = Dataset()
ds.addDefaultGraph('null')
tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString)
tupleQuery.setDataset(ds)
result = tupleQuery.evaluate();
print "SPARQL query over the null context."
for bindingSet in result:
print bindingSet.getRow()
print "---------------------------------------------------------------"
## testing named graph query:
queryString = """
SELECT ?s ?p ?o WHERE {?s ?p ?o . }
"""
ds = Dataset()
ds.addNamedGraph(context1)
tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString)
tupleQuery.setDataset(ds)
result = tupleQuery.evaluate();
print "SPARQL query over context1, no GRAPH pattern."
for bindingSet in result:
print bindingSet.getRow()
print "---------------------------------------------------------------"
## testing named graph query:
queryString = """
SELECT ?s ?p ?o ?c
WHERE { GRAPH ?c {?s ?p ?o . } }
"""
ds = Dataset()
ds.addNamedGraph(context1)
tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString)
tupleQuery.setDataset(ds)
result = tupleQuery.evaluate();
print "SPARQL query over context1, with GRAPH pattern."
for bindingSet in result:
print bindingSet.getRow()
print "---------------------------------------------------------------"
## testing named graph query:
queryString = """
SELECT ?s ?p ?o ?c
WHERE { GRAPH ?c {?s ?p ?o . } }
"""
tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString)
result = tupleQuery.evaluate();
print "SPARQL query with GRAPH pattern, no context constraints."
for bindingSet in result:
print bindingSet.getRow()
conn.close();
myRepository = conn.repository
myRepository.shutDown()
def example11():
"""
Namespaces
"""
print "Starting example11()."
conn = example1()
exns = "http://example.org/people/"
alice = conn.createURI(namespace=exns, localname="alice")
person = conn.createURI(namespace=exns, localname="Person")
conn.add(alice, RDF.TYPE, person)
conn.setNamespace('ex', exns)
#conn.removeNamespace('ex')
queryString = """
SELECT ?s ?p ?o
WHERE { ?s ?p ?o . FILTER ((?p = rdf:type) && (?o = ex:Person) ) }
"""
tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString)
result = tupleQuery.evaluate();
print
for bindingSet in result:
print bindingSet[0], bindingSet[1], bindingSet[2]
conn.close();
myRepository = conn.repository
myRepository.shutDown()
def example12():
"""
Text search
"""