本文整理汇总了Python中rdflib.graph.Graph.query方法的典型用法代码示例。如果您正苦于以下问题:Python Graph.query方法的具体用法?Python Graph.query怎么用?Python Graph.query使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类rdflib.graph.Graph
的用法示例。
在下文中一共展示了Graph.query方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: TestSPARQLToldBNodes
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import query [as 别名]
class TestSPARQLToldBNodes(unittest.TestCase):
manual = True
def setUp(self):
NS = u"http://example.org/"
self.graph = Graph(store)
self.graph.parse(
StringInputSource(
"""
@prefix : <http://example.org/> .
@prefix rdf: <%s> .
@prefix rdfs: <%s> .
[ :prop :val ].
[ a rdfs:Class ]."""
% (RDF, RDFS)
),
format="n3",
)
def testToldBNode(self):
for s, p, o in self.graph.triples((None, RDF.type, None)):
pass
query = """SELECT ?obj WHERE { %s ?prop ?obj }""" % s.n3()
print query
rt = self.graph.query(query, DEBUG=debug)
self.failUnless(len(rt) == 1, "BGP should only match the 'told' BNode by name (result set size: %s)" % len(rt))
bindings = {Variable("subj"): s}
query = """SELECT ?obj WHERE { ?subj ?prop ?obj }"""
print query
rt = self.graph.query(query, initBindings=bindings, DEBUG=debug)
self.failUnless(
len(rt) == 1,
"BGP should only match the 'told' BNode by name (result set size: %s, BNode: %s)" % (len(rt), s.n3()),
)
def testFilterBNode(self):
for s, p, o in self.graph.triples((None, RDF.type, None)):
pass
query2 = """SELECT ?subj WHERE { ?subj ?prop ?obj FILTER( ?subj != %s ) }""" % s.n3()
print query2
rt = self.graph.query(query2, DEBUG=True)
self.failUnless(
len(rt) == 1,
"FILTER should exclude 'told' BNodes by name (result set size: %s, BNode excluded: %s)" % (len(rt), s.n3()),
)
def tearDown(self):
self.graph.store.rollback()
示例2: testQueryMemoization
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import query [as 别名]
def testQueryMemoization(self):
topDownStore = TopDownSPARQLEntailingStore(
self.owlGraph.store,
self.owlGraph,
idb=self.program,
DEBUG=False,
nsBindings=nsMap,
decisionProcedure=BFP_METHOD,
identifyHybridPredicates=True)
targetGraph = Graph(topDownStore)
for pref, nsUri in nsMap.items():
targetGraph.bind(pref, nsUri)
goal = (Variable('SUBJECT'), RDF.type, EX.C)
queryLiteral = EDBQuery([BuildUnitermFromTuple(goal)],
self.owlGraph,
[Variable('SUBJECT')])
query = queryLiteral.asSPARQL()
rt = targetGraph.query(query, initNs=nsMap)
# if len(topDownStore.edbQueries) == len(set(topDownStore.edbQueries)):
# pprint(topDownStore.edbQueries)
_debug("Queries dispatched against EDB")
for query in self.owlGraph.queriesDispatched:
_debug(query)
self.failUnlessEqual(
len(self.owlGraph.queriesDispatched), 4, "Duplicate query")
示例3: bfp
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import query [as 别名]
def bfp(defaultDerivedPreds, options, factGraph, ruleSet, network,
hybridPredicates):
topDownDPreds = defaultDerivedPreds
if options.builtinTemplates:
builtinTemplateGraph = Graph().parse(options.builtinTemplates,
format='n3')
builtinDict = dict([
(pred, template) for pred, _ignore, template in
builtinTemplateGraph.triples(
(None, TEMPLATES.filterTemplate, None))])
else:
builtinDict = None
topDownStore = TopDownSPARQLEntailingStore(
factGraph.store,
factGraph,
idb=ruleSet,
DEBUG=options.debug,
derivedPredicates=topDownDPreds,
templateMap=builtinDict,
nsBindings=network.nsMap,
identifyHybridPredicates=options.hybrid,
hybridPredicates=hybridPredicates)
targetGraph = Graph(topDownStore)
for pref, nsUri in list(network.nsMap.items()):
targetGraph.bind(pref, nsUri)
start = time.time()
sTime = time.time() - start
result = targetGraph.query(options.why, initNs=network.nsMap)
if result.askAnswer:
sTime = time.time() - start
if sTime > 1:
sTimeStr = "%s seconds" % sTime
else:
sTime = sTime * 1000
sTimeStr = "%s milli seconds" % sTime
print("Time to reach answer ground goal answer of %s: %s" % (
result.askAnswer[0], sTimeStr))
else:
for rt in result:
sTime = time.time() - start
if sTime > 1:
sTimeStr = "%s seconds" % sTime
else:
sTime = sTime * 1000
sTimeStr = "%s milli seconds" % sTime
if options.firstAnswer:
break
print("Time to reach answer %s via top-down SPARQL"
" sip strategy: %s" % (rt, sTimeStr))
if options.output == 'conflict' and options.method == 'bfp':
for _network, _goal in topDownStore.queryNetworks:
print(network, _goal)
_network.reportConflictSet(options.debug)
for query in topDownStore.edbQueries:
print(query.asSPARQL())
示例4: WhichSubsumptionOperand
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import query [as 别名]
def WhichSubsumptionOperand(term, owlGraph):
topDownStore = TopDownSPARQLEntailingStore(
owlGraph.store,
owlGraph,
idb=HornFromN3(StringIO(SUBSUMPTION_SEMANTICS)),
DEBUG=False,
derivedPredicates=[OWL_NS.sameAs],
hybridPredicates=[OWL_NS.sameAs])
targetGraph = Graph(topDownStore)
appearsLeft = targetGraph.query(
"ASK { <%s> rdfs:subClassOf [] } ",
initNs={'rdfs': RDFS})
appearsRight = targetGraph.query(
"ASK { [] rdfs:subClassOf <%s> } ",
initNs={'rdfs': RDFS})
if appearsLeft and appearsRight:
return BOTH_SUBSUMPTION_OPERAND
elif appearsLeft:
return LEFT_SUBSUMPTION_OPERAND
else:
return RIGHT_SUBSUMPTION_OPERAND
示例5: AdvancedTests
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import query [as 别名]
class AdvancedTests(unittest.TestCase):
def setUp(self):
memStore = plugin.get('IOMemory',Store)()
self.testGraph = Graph(memStore)
self.testGraph.parse(StringIO(testGraph1N3),format='n3')
def testNamedGraph(self):
from sets import Set
OWL_NS = Namespace("http://www.w3.org/2002/07/owl#")
rt = self.testGraph.query(sparqlQ4)
self.assertEquals(Set(rt.serialize('python')),Set([OWL_NS.OntologyProperty,OWL_NS.Class,OWL_NS.Ontology,OWL_NS.AnnotationProperty,RDF.Property,RDFS.Class]))
def testScopedBNodes(self):
rt = self.testGraph.query(sparqlQ1)
self.assertEquals(rt.serialize('python')[0],URIRef("http://test/foo"))
def testCollectionContentWithinAndWithout(self):
rt = self.testGraph.query(sparqlQ3)
self.assertEquals(rt.serialize('python')[0],URIRef("http://test/bar"))
def testCollectionAsObject(self):
rt = self.testGraph.query(sparqlQ2)
self.assertEquals(rt.serialize('python')[0],URIRef("http://test/foo"))
self.assertEquals(1,len(rt))
示例6: testTransitivity
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import query [as 别名]
def testTransitivity(self):
raise SkipTest("SKIPFAIL testTransitivity, see test/test_sameAs.py")
nsBindings = {u'owl': OWL_NS, u'ex': EX}
topDownStore = TopDownSPARQLEntailingStore(
self.graph.store,
self.graph,
idb=HornFromN3(StringIO(RULES)),
DEBUG=True,
derivedPredicates=[OWL_NS.sameAs],
nsBindings=nsBindings,
hybridPredicates=[OWL_NS.sameAs])
targetGraph = Graph(topDownStore)
for query, solns in QUERIES.items():
result = set(targetGraph.query(query, initNs=nsBindings))
print(query, result)
self.failUnless(not solns.difference(result))
示例7: testTransitivity
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import query [as 别名]
def testTransitivity(self):
nsBindings = {u"owl": OWL_NS, u"ex": EX}
topDownStore = TopDownSPARQLEntailingStore(
self.graph.store,
self.graph,
idb=HornFromN3(StringIO(RULES)),
DEBUG=True,
derivedPredicates=[OWL_NS.sameAs],
nsBindings=nsBindings,
hybridPredicates=[OWL_NS.sameAs],
)
targetGraph = Graph(topDownStore)
for query, solns in QUERIES.items():
result = set(targetGraph.query(query, initNs=nsBindings))
print query, result
self.failUnless(not solns.difference(result))
示例8: GraphAggregates3
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import query [as 别名]
class GraphAggregates3(unittest.TestCase):
def setUp(self):
memStore = plugin.get("SQLAlchemy", Store)(identifier="rdflib_test", configuration=Literal("sqlite://"))
self.graph1 = Graph(memStore, URIRef("graph1"))
self.graph2 = Graph(memStore, URIRef("graph2"))
self.graph3 = Graph(memStore, URIRef("graph3"))
for n3Str, graph in [(testGraph1N3, self.graph1), (testGraph2N3, self.graph2), (testGraph3N3, self.graph3)]:
graph.parse(StringIO(n3Str), format="n3")
self.G = ConjunctiveGraph(memStore)
def testDefaultGraph(self):
# test that CG includes triples from all 3
assert self.G.query(sparqlQ3), "CG as default graph should *all* triples"
assert not self.graph2.query(sparqlQ3), (
"Graph as " + "default graph should *not* include triples from other graphs"
)
示例9: GraphAggregates3
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import query [as 别名]
class GraphAggregates3(unittest.TestCase):
def setUp(self):
memStore = plugin.get('IOMemory',Store)()
self.graph1 = Graph(memStore,URIRef("graph1"))
self.graph2 = Graph(memStore,URIRef("graph2"))
self.graph3 = Graph(memStore,URIRef("graph3"))
for n3Str,graph in [(testGraph1N3,self.graph1),
(testGraph2N3,self.graph2),
(testGraph3N3,self.graph3)]:
graph.parse(StringIO(n3Str),format='n3')
self.G = ConjunctiveGraph(memStore)
def testDefaultGraph(self):
#test that CG includes triples from all 3
assert self.G.query(sparqlQ3),"CG as default graph should *all* triples"
assert not self.graph2.query(sparqlQ3),"Graph as default graph should *not* include triples from other graphs"
示例10: testTransitivity
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import query [as 别名]
def testTransitivity(self):
# from nose.exc import SkipTest
# raise SkipTest("fails with Exception in SidewaysInformationPassing")
nsBindings = {u'owl': OWL_NS, u'ex': EX}
topDownStore = TopDownSPARQLEntailingStore(
self.graph.store,
self.graph,
idb=HornFromN3(StringIO(RULES)),
DEBUG=False,
derivedPredicates=[OWL_NS.sameAs],
nsBindings=nsBindings,
hybridPredicates=[OWL_NS.sameAs])
targetGraph = Graph(topDownStore)
for query, solns in QUERIES.items():
_debug("query {}".format(query))
_debug("solutions {}".format(solns))
result = set(targetGraph.query(query, initNs=nsBindings))
_debug("result {}".format(result))
self.failUnless(not solns.difference(result))
示例11: check_for_semantic
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import query [as 别名]
def check_for_semantic((dataset, uri_pattern, identifier, configString)):
# print configString
# print identifier
g = Graph(store="PostgreSQL", identifier=identifier)
# print identifier, configString
g.open(configString, create=False)
# print len(g)
# print g
objs = get_obj_from_prefix(dataset, g, uri_pattern)
# print objs
# headers = {"Accept": "application/rdf+xml"}
linksets = {}
# print dataset, len(objs)
for obj in objs:
try:
# conn = httplib.HTTPConnection(url.netloc, timeout=30)
# conn.request("GET", url.path, "", headers)
# print str(obj[0])
request = urllib2.Request(str(obj[0]))
request.add_header("Accept", "application/rdf+xml")
response = urllib2.urlopen(request)
# response = conn.getresponse()
# print response.headers['content-type']
# print str(obj[0]), response.code
if "application/rdf+xml" in response.headers["content-type"]:
query = "SELECT ?p WHERE {?s ?p <" + str(obj[0]) + ">}"
qres = g.query(query)
result = qres.result
for p in result:
if dataset in linksets:
if str(p[0]) in linksets[dataset]:
linksets[dataset][str(p[0])] = linksets[dataset][str(p[0])] + 1
else:
linksets[dataset][str(p[0])] = 1
else:
linksets[dataset] = {str(p[0]): 1}
except Exception as e:
print e
# print dataset + ' timed out!'
return linksets
# print linksets
return linksets
示例12: parsefoaf
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import query [as 别名]
def parsefoaf(self, location, pub, topic, callback):
"""
Method: parsefoaf(location)
@param location:Either the location or the foaf profile as a string
Parses the foaf profile and provides the URI of the person who is represented in the FOAF
Returns graph, person's uri
TODO: Before the foaf triples are sent, need to check whether the publisher or the
subscriber are already in the rdf store.
"""
store = Graph()
store.bind("dc", "http://http://purl.org/dc/elements/1.1/")
store.bind("foaf", "http://xmlns.com/foaf/0.1/")
foaf = get_private_uri(location, HUB_CERTIFICATE, HUB_KEY)
store.parse(data=foaf, format="application/rdf+xml")
#store.parse("http://www.w3.org/People/Berners-Lee/card.rdf")
#for person in store.subjects(RDF.type, FOAF["Person"]):
#print "Person:"+person
qres = store.query(
"""SELECT DISTINCT ?a
WHERE {
?a a <http://xmlns.com/foaf/0.1/Person> .
?b <http://xmlns.com/foaf/0.1/primaryTopic> ?a .
}""")
person_URI = ''
for row in qres.result:
person_URI = row
# Check whether the foaf of the person is already present in the rdf store.
# To speed up the execution we can keep a cache of the person_URIs whose foaf profiles
# are present.
logging.info("Checking whether foaf: %s is already present in the RDF store", person_URI)
if self.triple_store.foaf_exists(person_URI):
store = Graph()
logging.info("foaf: %s is already present in the RDF store", person_URI)
# Add the rest of the required triples to the graph
store = self.addTriples(store, person_URI, pub, topic, callback)
# Transform the graph to triples
triples = self.to_tuples(store, location)
return triples
示例13: TestSPARQLAbbreviations
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import query [as 别名]
class TestSPARQLAbbreviations(unittest.TestCase):
sparql = True
def setUp(self):
NS = u"http://example.org/"
self.graph = Graph(store)
self.graph.parse(StringInputSource(b("""
@prefix : <http://example.org/> .
@prefix rdf: <%s> .
@prefix rdfs: <%s> .
[ :prop :val ].
[ a rdfs:Class ]."""%(RDF,RDFS))), format="n3")
def testTypeAbbreviation(self):
query = """SELECT ?subj WHERE { ?subj a rdfs:Class }"""
print query
rt = self.graph.query(query,DEBUG=debug)
self.failUnless(len(rt) == 1,"Should be a single match: %s"%len(rt))
query = """SELECT ?subj WHERE { ?subj a <http://www.w3.org/2000/01/rdf-schema#Class> }"""
print query
rt = self.graph.query(query,DEBUG=debug)
self.failUnless(len(rt) == 1,"Should be a single match: %s"%len(rt))
def testTypeAbbreviation(self):
query = """SELECT ?subj WHERE { ?subj a rdfs:Class }"""
print query
rt = self.graph.query(query,DEBUG=debug)
self.failUnless(len(rt) == 1,"Should be a single match: %s"%len(rt))
query = """SELECT ?subj WHERE { ?subj a <http://www.w3.org/2000/01/rdf-schema#Class> }"""
print query
rt = self.graph.query(query,DEBUG=debug)
self.failUnless(len(rt) == 1,"Should be a single match: %s"%len(rt))
def testQNameVSFull(self):
query = """SELECT ?subj WHERE { ?subj <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> rdfs:Class }"""
print query
rt = self.graph.query(query,DEBUG=debug)
self.failUnless(len(rt) == 1,"Should be a single matchL: %s"%len(rt))
query = """SELECT ?subj WHERE { ?subj <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2000/01/rdf-schema#Class> }"""
print query
rt = self.graph.query(query,DEBUG=debug)
self.failUnless(len(rt) == 1,"Should be a single match: %s"%len(rt))
def tearDown(self):
self.graph.store.rollback()
示例14: get_current_version
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import query [as 别名]
def get_current_version(self):
""" Get Virtuoso Database Graph Current Version """
query = """\
prefix owl: <http://www.w3.org/2002/07/owl#>
prefix xsd: <http://www.w3.org/2001/XMLSchema#>
select distinct ?version ?origen
FROM <%(m_graph)s>
{{
select distinct ?version ?origen ?data
FROM <%(m_graph)s>
where {?s owl:versionInfo ?version;
<%(m_graph)scommited> ?data;
<%(m_graph)sproduto> "%(v_graph)s";
<%(m_graph)sorigen> ?origen.}
ORDER BY desc(?data) LIMIT 1
}}""" % {'m_graph': self.migration_graph, 'v_graph': self.__virtuoso_graph}
graph = Graph(store="SPARQLStore")
graph.open(self.__virtuoso_endpoint, create=False)
graph.store.baseURI = self.__virtuoso_endpoint
ns = list(graph.namespaces())
assert len(ns) > 0, ns
res = graph.query(query)
graph.close()
nroResults = len(res)
if nroResults > 0:
res.vars = ['version', 'origen']
versao, origem = iter(res).next()
versao = None if str(versao) == 'None' else str(versao)
return versao, str(origem)
else:
return None, None
示例15: MagicOWLProof
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import query [as 别名]
def MagicOWLProof(self, goals, rules, factGraph, conclusionFile):
progLen = len(rules)
magicRuleNo = 0
dPreds = []
for rule in AdditionalRules(factGraph):
rules.append(rule)
if not GROUND_QUERY and REASONING_STRATEGY != 'gms':
goalDict = dict([((Variable('SUBJECT'),goalP,goalO),goalS)
for goalS,goalP,goalO in goals])
goals = goalDict.keys()
assert goals
if REASONING_STRATEGY == 'gms':
for rule in MagicSetTransformation(factGraph,
rules,
goals,
dPreds):
magicRuleNo += 1
self.network.buildNetworkFromClause(rule)
self.network.rules.add(rule)
if DEBUG:
print("\t%s" % rule)
print("rate of reduction in the size of the program: %s " % (
100 - (float(magicRuleNo) / float(progLen)) * 100))
if REASONING_STRATEGY in ['bfp', 'sld']: # and not GROUND_QUERY:
reasoningAlg = TOP_DOWN_METHOD if REASONING_STRATEGY == 'sld' \
else BFP_METHOD
topDownStore = TopDownSPARQLEntailingStore(
factGraph.store,
factGraph,
idb=rules,
DEBUG=DEBUG,
nsBindings=nsMap,
decisionProcedure=reasoningAlg,
identifyHybridPredicates=REASONING_STRATEGY == 'bfp')
targetGraph = Graph(topDownStore)
for pref,nsUri in nsMap.items():
targetGraph.bind(pref,nsUri)
start = time.time()
for goal in goals:
queryLiteral = EDBQuery([BuildUnitermFromTuple(goal)],
factGraph,
None if GROUND_QUERY else [goal[0]])
query = queryLiteral.asSPARQL()
print "Goal to solve ", query
rt = targetGraph.query(query, initNs=nsMap)
if GROUND_QUERY:
self.failUnless(rt.askAnswer[0],"Failed top-down problem")
else:
if (goalDict[goal]) not in rt or DEBUG:
for network,_goal in topDownStore.queryNetworks:
print network,_goal
network.reportConflictSet(True)
for query in topDownStore.edbQueries:
print query.asSPARQL()
self.failUnless((goalDict[goal]) in rt,
"Failed top-down problem")
sTime = time.time() - start
if sTime > 1:
sTimeStr = "%s seconds" % sTime
else:
sTime = sTime * 1000
sTimeStr = "%s milli seconds" % sTime
return sTimeStr
elif REASONING_STRATEGY == 'gms':
for goal in goals:
adornedGoalSeed = AdornLiteral(goal).makeMagicPred()
goal = adornedGoalSeed.toRDFTuple()
if DEBUG:
print("Magic seed fact %s" % adornedGoalSeed)
factGraph.add(goal)
timing = self.calculateEntailments(factGraph)
for goal in goals:
# self.failUnless(goal in self.network.inferredFacts or goal in factGraph,
# "Failed GMS query")
if goal not in self.network.inferredFacts and goal not in factGraph:
print("missing triple %s" % (pformat(goal)))
pprint(list(factGraph.adornedProgram))
# from FuXi.Rete.Util import renderNetwork
# dot=renderNetwork(self.network,self.network.nsMap).write_jpeg('test-fail.jpeg')
self.network.reportConflictSet(True)
raise # Exception ("Failed test: "+feature)
else:
print("=== Passed! ===")
return timing