1""" 2An RDFLib ConjunctiveGraph is an (unnamed) aggregation of all the named graphs 3within a Store. The :meth:`~rdflib.graph.ConjunctiveGraph.get_context` 4method can be used to get a particular named graph for use such as to add 5triples to, or the default graph can be used 6 7This example shows how to create named graphs and work with the 8conjunction (union) of all the graphs. 9""" 10 11from rdflib import Namespace, Literal, URIRef 12from rdflib.graph import Graph, ConjunctiveGraph 13from rdflib.plugins.memory import IOMemory 14 15if __name__ == "__main__": 16 17 ns = Namespace("http://love.com#") 18 19 mary = URIRef("http://love.com/lovers/mary") 20 john = URIRef("http://love.com/lovers/john") 21 22 cmary = URIRef("http://love.com/lovers/mary") 23 cjohn = URIRef("http://love.com/lovers/john") 24 25 store = IOMemory() 26 27 g = ConjunctiveGraph(store=store) 28 g.bind("love", ns) 29 30 # add a graph for Mary's facts to the Conjunctive Graph 31 gmary = Graph(store=store, identifier=cmary) 32 # Mary's graph only contains the URI of the person she love, not his cute name 33 gmary.add((mary, ns["hasName"], Literal("Mary"))) 34 gmary.add((mary, ns["loves"], john)) 35 36 # add a graph for Mary's facts to the Conjunctive Graph 37 gjohn = Graph(store=store, identifier=cjohn) 38 # John's graph contains his cute name 39 gjohn.add((john, ns["hasCuteName"], Literal("Johnny Boy"))) 40 41 # enumerate contexts 42 for c in g.contexts(): 43 print("-- %s " % c) 44 45 # separate graphs 46 print(gjohn.serialize(format="n3").decode("utf-8")) 47 print("===================") 48 print(gmary.serialize(format="n3").decode("utf-8")) 49 print("===================") 50 51 # full graph 52 print(g.serialize(format="n3").decode("utf-8")) 53 54 # query the conjunction of all graphs 55 xx = None 56 for x in g[mary: ns.loves / ns.hasCuteName]: 57 xx = x 58 print("Q: Who does Mary love?") 59 print("A: Mary loves {}".format(xx)) 60