How to search for an rdf object, knowing the subject or vice versa?

I use RDFLIB to plot among 3 datasets (A, B, C) with ntriples.

Objectives: the graphs contain links between these datasets A-> B, B-> C and C-> A, I want to check the consistency of these links, making sure that the links coming from A go back to the same entries in A.

Problem: as soon as I iterate over links in A-> B, I wanted to find the corresponding records (maybe more than one) in B-> C and the same for C-> A, there is a way to search for objects, knowing the subject without repeating all the records ?

+4
source share
1 answer

Is there a way to search for objects, knowing the subject without repeating all the records?

Answer: Yes. And you can use various mechanisms: (a) iteration with restriction; or (b) issue a SPARQL query.

(a) restricts the schedule and iterates

This solution uses the RDFLib triples function over the Graph object. See this link .

 #Parse the file g = rdflib.Graph() g.parse("yourdata.nquads") subject = article = rdflib.term.URIRef("http://www.someuri.org/for/your/subject") # (subject,None,None) represents a constrain to iterate over the graph. By setting # any of the three elements in the triple you constrain by any combination of subject, # predicate or object. In this case we only constrain by subject. for triple in g.triples((subject,None,None)): print triple 

(b) issue a SPARQL query

A more standard solution using the SPARQL standard .

 rdflib.plugin.register('sparql', rdflib.query.Processor, 'rdfextras.sparql.processor', 'Processor') rdflib.plugin.register('sparql', rdflib.query.Result, 'rdfextras.sparql.query', 'SPARQLQueryResult') #Parse the file g = rdflib.Graph() g.parse("yourdata.nquads") query = """ SELECT ?pred ?obj WHERE { <http://www.someuri.org/for/your/subject> ?pred ?obj } """ for row in g.query(query): print "Predicate:%s Object:%s"%(row[0],row[1]) 
+5
source

Source: https://habr.com/ru/post/1342000/


All Articles