5.3.2 SPARQLにおける接頭辞の扱い
owlready2とRDFlibでは、SPARQLでのクエリー文を記述しやすくするために、接頭辞(prefix)が利用できる。
| graph.bind([prefix], [base IRI]) |
|---|
として、接頭辞とIRI(フラグメントまでの部分)を結び付ければよい。例を示す。
>>> from owlready2 import *
>>> onto = get_ontology('bacteria.owl').load()
>>> from rdflib import *
>>> graph = default_world.as_rdflib_graph()
>>> graph.bind('owl', 'http://www.w3.org/2002/07/owl#')
>>> onto.base_iri
'http://lesfleursdunormal.fr/static/_downloads/bacteria.owl#'
>>> individual = onto.unknown_bacterium
>>> list(default_world.sparql_query('''
... SELECT ?class WHERE{
... <%s> a ?class .
... ?class a owl:Class .
... }''' % individual.iri))
[[bacteria.Bacterium]]
5.3.3 SPARQLでRDFトリプルを作成する
SPARQLではINSERT文によりRDFトリプルを作成する。RDFトリプルの作成にはupdate()メソッドを使う。
RDFトリプルの作成には、with構文を使う方法とget_context()メソッドを使う方法がある。例を示す。
>>> with onto:
... graph.update('''
... INSERT {
... <http://www.test.org/t.owl#MyClass>
... <http://www.w3.org/1999/02/22-rdf-syntax-ns#type>
... <http://www.w3.org/2002/07/owl#Class> .
... } WHERE {}''')
...
>>>
>>> graph2 = graph.get_context(onto)
>>> graph2.update('''
... INSERT {
... <http://www.test.org/t.owl#MyClass2>
... <http://www.w3.org/1999/02/22-rdf-syntax-ns#type>
... <http://www.w3.org/2002/07/owl#Class> .
... } WHERE {}''')
検索すると、生成されたことが確認できる。
>>> ret = graph.query("""
... SELECT ?b WHERE {
... ?b
... <http://www.w3.org/1999/02/22-rdf-syntax-ns#type>
... <http://www.w3.org/2002/07/owl#Class> .
... }""" )
>>> list(ret)
[(rdflib.term.BNode('35'),),
~~~
(rdflib.term.URIRef('http://www.test.org/t.owl#MyClass'),),
(rdflib.term.URIRef('http://www.test.org/t.owl#MyClass2'),)]
WHERE句を利用する場合、既に存在するクラスやインディビデュアル関連する、RDFトリプルを生成できる。例えば、クラスにコメントのRDFトリプルを追加するものである。
>>> graph2.update('''
... INSERT {
... ?class
... <http://www.w3.org/2000/01/rdf-schema#comment>
... "This entity is a class!."
... }WHERE{
... ?class a <http://www.w3.org/2002/07/owl#Class> .
... }
... ''')
>>> list(graph.query("""
... SELECT ?b ?c WHERE {
... ?b
... <http://www.w3.org/2000/01/rdf-schema#comment>
... ?c
... }""" ))
[(rdflib.term.URIRef('http://lesfleursdunormal.fr/static/_downloads/bacteria.owl#Shape'), rdflib.term.Literal('This entity is a class!.')),
~
(rdflib.term.URIRef('http://www.test.org/t.owl#MyClass'), rdflib.term.Literal('This entity is a class!.')),
~
(rdflib.term.URIRef('http://www.test.org/t.owl#MyClass2'), rdflib.term.Literal('This entity is a class!.')),
~]
5.3.4 SPARQLでRDFトリプルを削除する
RDFトリプルの削除にはupdate()メソッドを使う。SPARQLの問い合わせはDELETE文となる。
>>> graph2.update('''
... DELETE{
... ?class
... <http://www.w3.org/2000/01/rdf-schema#comment>
... "This entity is a class!."
... }WHERE{
... ?class a <http://www.w3.org/2002/07/owl#Class> .
... }
... ''')
>>> list(graph.query("""
... SELECT ?b ?c WHERE {
... ?b
... <http://www.w3.org/2000/01/rdf-schema#comment>
... ?c
... }""" ))
...
[]