user0221441
user0221441

Reputation: 346

how to pattern match triples using rdflib without using SPARQL

I want to pattern match triples of an existing RDF graph. The triples() function of the RDFLib module looks like it could do the job, but I cant get it to work.

Can someone provide an example?

Consider the following graph.

@prefix ex: <http://example.com/family/> .

ex:Bob a ex:Person.
ex:Bob ex:Occupation ex:Doctor.
ex:Bob ex:Country ex:USA.
ex:Bob ex:Age ex:32.

I would like to pattern match all triples with subject ex:Bob.

I have a hunch I am using the wrong function to begin with. Can someone explain? Thanks

Upvotes: 0

Views: 761

Answers (1)

Stanislav Kralin
Stanislav Kralin

Reputation: 11469

import rdflib
g = rdflib.Graph()
g.parse("bob.ttl", format="turtle")

bob = rdflib.URIRef("http://example.com/family/Bob")

for triple in g.triples( (bob, None, None) ):
    print(triple)

family = rdflib.Namespace('http://example.com/family/')
bob = family.Bob

for triple in g.triples( (bob, None, None) ):
    print(triple)

Note that triple patterns, as well as triples themselves, are Python tuples in RDFLib; hence one more pair of parentheses.

Upvotes: 1

Related Questions