Lab Solutions: Difference between revisions
No edit summary |
No edit summary |
||
Line 520: | Line 520: | ||
g.add((ex.capital, RDFS.subPropertyOf, ex.hasLocation)) | g.add((ex.capital, RDFS.subPropertyOf, ex.hasLocation)) | ||
# That someone was involved in a meeting, means that they have met the other participants. | # That someone was involved in a meeting, means that they have met the other participants. | ||
# This question was bad for the RDFS lab because we need OWL | # This question was bad for the RDFS lab because we need complex OWL or easy sparql. | ||
res = g.query(""" | |||
CONSTRUCT {?person1 ex:haveMet ?person2} | |||
WHERE { | |||
?person1 ex:meeting ?Meeting . | |||
?Meeting ex:involved ?person2 . | |||
} | |||
""") | |||
for triplet in res: | |||
#we don't need to add that people have met themselves | |||
if (triplet[0] != triplet[2]): | |||
g.add((triplet)) | |||
# If someone partook in a meeting somewhere, means that they have visited that place" | # If someone partook in a meeting somewhere, means that they have visited that place" | ||
# This question was bad for the RDFS lab | # This question was bad for the RDFS lab for the same reason. | ||
res = g.query(""" | |||
CONSTRUCT {?person ex:hasVisited ?place} | |||
WHERE { | |||
?person1 ex:meeting ?Meeting . | |||
?Meeting ex:location ?place . | |||
} | |||
""") | |||
for triplet in res: | |||
g.add((triplet)) | |||
rdfs = owlrl.OWLRL.OWLRL_Semantics(g, False, False, False) | rdfs = owlrl.OWLRL.OWLRL_Semantics(g, False, False, False) |
Revision as of 14:57, 11 March 2022
This page will be updated with Python examples related to the lectures and labs. We will add more examples after each lab has ended. The first examples will use Python's RDFlib. We will introduce other relevant libraries later.
Example lab solutions
Getting started
from rdflib.collection import Collection
from rdflib import Graph, Namespace, Literal, URIRef
from rdflib.namespace import RDF, FOAF, XSD
g = Graph()
EX = Namespace('http://EXample.org/')
RL = Namespace('http://purl.org/vocab/relationship/')
DBO = Namespace('https://dbpedia.org/ontology/')
DBR = Namespace('https://dbpedia.org/page/')
g.namespace_manager.bind('exampleURI', EX)
g.namespace_manager.bind('relationship', RL)
g.namespace_manager.bind('dbpediaOntology', DBO)
g.namespace_manager.bind('dbpediaPage', DBR)
g.add((EX.Cade, RDF.type, FOAF.Person))
g.add((EX.Mary, RDF.type, FOAF.Person))
g.add((EX.Cade, RL.spouseOf, EX.Mary)) # a symmetrical relation from an established namespace
g.add((DBR.France, DBO.capital, DBR.Paris))
g.add((EX.Cade, FOAF.age, Literal(27)))
g.add((EX.Mary, FOAF.age, Literal('26', datatype=XSD.int)))
Collection (g, EX.MaryInterests, [EX.hiking, EX.choclate, EX.biology])
g.add((EX.Mary, EX.hasIntrest, EX.MaryInterests))
g.add((EX.Mary, RDF.type, EX.student))
g.add((DBO.capital, EX.range, EX.city))
g.add((EX.Mary, RDF.type, EX.kind))
g.add((EX.Cade, RDF.type, EX.kindPerson))
#hobbies = ['hiking', 'choclate', 'biology']
#for i in hobbies:
# g.add((EX.Mary, FOAF.interest, EX[i]))
print(g.serialize(format="turtle"))
RDFlib
from rdflib.namespace import RDF, XSD, FOAF
from rdflib import Graph, Namespace, Literal, BNode
from rdflib.collection import Collection
g = Graph()
ex = Namespace('http://example.org/')
schema = Namespace("https://schema.org/")
dbp = Namespace("https://dbpedia.org/resource/")
g.bind("ex", ex)
g.bind("dbp", dbp)
g.bind("schema", schema)
address = BNode()
degree = BNode()
# from lab 1
g.add((ex.Cade, FOAF.name, Literal("Cade Tracey", datatype=XSD.string)))
g.add((ex.Mary, FOAF.name, Literal("Mary", datatype=XSD.string)))
g.add((ex.Cade, RDF.type, FOAF.Person))
g.add((ex.Mary, RDF.type, FOAF.Person))
g.add((ex.Mary, RDF.type, ex.Student))
g.add((ex.Cade, ex.married, ex.Mary))
g.add((ex.Cade, FOAF.age, Literal('27', datatype=XSD.int)))
g.add((ex.Mary, FOAF.age, Literal('26', datatype=XSD.int)))
g.add((ex.Paris, RDF.type, ex.City))
g.add((ex.France, ex.Capital, ex.Paris))
g.add((ex.Mary, FOAF.interest, ex.hiking))
g.add((ex.Mary, FOAF.interest, ex.Chocolate))
g.add((ex.Mary, FOAF.interest, ex.biology))
g.add((ex.France, ex.City, ex.Paris))
g.add((ex.Mary, ex.Characterostic, ex.kind))
g.add((ex.Cade, ex.Characterostic, ex.kind))
g.add((ex.France, RDF.type, ex.Country))
g.add((ex.Cade, schema.address, address))
# BNode address
g.add((address, RDF.type, schema.PostalAdress))
g.add((address, schema.streetAddress, Literal('1516 Henry Street')))
g.add((address, schema.addresCity, dbp.Berkeley))
g.add((address, schema.addressRegion, dbp.California))
g.add((address, schema.postalCode, Literal('94709')))
g.add((address, schema.addressCountry, dbp.United_States))
# More info about Cade
g.add((ex.Cade, ex.Degree, degree))
g.add((degree, ex.Field, dbp.Biology))
g.add((degree, RDF.type, dbp.Bachelors_degree))
g.add((degree, ex.Universety, dbp.University_of_California))
g.add((degree, ex.year, Literal('2001', datatype=XSD.gYear)))
# Emma
emma_degree = BNode()
g.add((ex.Emma, FOAF.name, Literal("Emma Dominguez", datatype=XSD.string)))
g.add((ex.Emma, RDF.type, FOAF.Person))
g.add((ex.Emma, ex.Degree, emma_degree))
g.add((degree, ex.Field, dbp.Chemistry))
g.add((degree, RDF.type, dbp.Masters_degree))
g.add((degree, ex.Universety, dbp.University_of_Valencia))
g.add((degree, ex.year, Literal('2015', datatype=XSD.gYear)))
# Address
emma_address = BNode()
g.add((ex.Emma, schema.address, emma_address))
g.add((emma_address, RDF.type, schema.PostalAdress))
g.add((emma_address, schema.streetAddress,
Literal('Carrer de la Guardia Civil 20')))
g.add((emma_address, schema.addressRegion, dbp.Valencia))
g.add((emma_address, schema.postalCode, Literal('46020')))
g.add((emma_address, schema.addressCountry, dbp.Spain))
b = BNode()
g.add((ex.Emma, ex.visit, b))
Collection(g, b,
[dbp.Portugal, dbp.Italy, dbp.France, dbp.Germany, dbp.Denmark, dbp.Sweden])
SPARQL - Blazegraph
PREFIX ex: <http://example.org/>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX xml: <http://www.w3.org/XML/1998/namespace>
PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
#select all triplets in graph
SELECT ?s ?p ?o
WHERE {
?s ?p ?o .
}
#select the interestes of Cade
SELECT ?cadeInterest
WHERE {
ex:Cade ex:interest ?cadeInterest .
}
#select the country and city where Emma lives
SELECT ?emmaCity ?emmaCountry
WHERE {
ex:Emma ex:address ?address .
?address ex:city ?emmaCity .
?address ex:country ?emmaCountry .
}
#select the people who are over 26 years old
SELECT ?person ?age
WHERE {
?person ex:age ?age .
FILTER(?age > 26) .
}
#select people who graduated with Bachelor
SELECT ?person ?degree
WHERE {
?person ex:degree ?degree .
?degree ex:degreeLevel "Bachelor" .
}
# delete cades photography interest
DELETE DATA
{
ex:Cade ex:interest ex:Photography .
}
# delete and insert university of valencia
DELETE { ?s ?p ex:University_of_Valencia }
INSERT { ?s ?p ex:Universidad_de_Valencia }
WHERE { ?s ?p ex:University_of_Valencia }
#check if the deletion worked
SELECT ?s ?o2
WHERE {
?s ex:degree ?o .
?o ex:degreeSource ?o2 .
}
#describe sergio
DESCRIBE ex:Sergio ?o
WHERE {
ex:Sergio ?p ?o .
?o ?p2 ?o2 .
}
SPARQL - RDFlib
from SPARQLWrapper import SPARQLWrapper, JSON, POST, GET, TURTLE
namespace = "lab4"
sparql = SPARQLWrapper("http://10.111.21.183:9999/blazegraph/namespace/"+ namespace + "/sparql")
# Print out Cades interests
sparql.setQuery("""
PREFIX ex: <http://example.org/>
SELECT * WHERE {
ex:Cade ex:interest ?interest.
}
""")
sparql.setReturnFormat(JSON)
results = sparql.query().convert()
for result in results["results"]["bindings"]:
print(result["interest"]["value"])
# Print Emmas city and country
sparql.setQuery("""
PREFIX ex: <http://example.org/>
SELECT ?emmaCity ?emmaCountry
WHERE {
ex:Emma ex:address ?address .
?address ex:city ?emmaCity .
?address ex:country ?emmaCountry .
}
""")
sparql.setReturnFormat(JSON)
results = sparql.query().convert()
for result in results["results"]["bindings"]:
print("Emma's city is "+result["emmaCity"]["value"]+" and Emma's country is " + result["emmaCountry"]["value"])
#Select the people who are over 26 years old
sparql.setQuery("""
PREFIX ex: <http://example.org/>
SELECT ?person ?age
WHERE {
?person ex:age ?age .
FILTER(?age > 26) .
}
""")
sparql.setReturnFormat(JSON)
results = sparql.query().convert()
for result in results["results"]["bindings"]:
print("All people who are over 26 years old: "+result["person"]["value"])
#Select people who graduated with Bachelor
sparql.setQuery("""
PREFIX ex: <http://example.org/>
SELECT ?person ?degree
WHERE {
?person ex:degree ?degree .
?degree ex:degreeLevel "Bachelor" .
}
""")
sparql.setReturnFormat(JSON)
results = sparql.query().convert()
for result in results["results"]["bindings"]:
print("People who graduated with Bachelor: "+result["person"]["value"])
#Delete cades photography interest
sparql.setQuery("""
PREFIX ex: <http://example.org/>
DELETE DATA {
ex:Cade ex:interest ex:Photography .
}
""")
sparql.setMethod(POST)
results = sparql.query()
print(results.response.read())
# Print out Cades interests again
sparql.setQuery("""
PREFIX ex: <http://example.org/>
SELECT * WHERE {
ex:Cade ex:interest ?interest.
}
""")
sparql.setReturnFormat(JSON)
sparql.setMethod(GET)
results = sparql.query().convert()
for result in results["results"]["bindings"]:
print(result["interest"]["value"])
# Check university names
sparql.setQuery("""
PREFIX ex: <http://example.org/>
SELECT ?s ?o2
WHERE {
?s ex:degree ?o .
?o ex:degreeSource ?o2 .
}
""")
sparql.setReturnFormat(JSON)
results = sparql.query().convert()
for result in results["results"]["bindings"]:
print(result["o2"]["value"])
#Delete and insert university of valencia
sparql.setQuery("""
PREFIX ex: <http://example.org/>
DELETE { ?s ?p ex:University_of_Valencia }
INSERT { ?s ?p ex:Universidad_de_Valencia }
WHERE { ?s ?p ex:University_of_Valencia }
""")
sparql.setMethod(POST)
results = sparql.query()
print(results.response.read())
# Check university names again
sparql.setQuery("""
PREFIX ex: <http://example.org/>
SELECT ?s ?o2
WHERE {
?s ex:degree ?o .
?o ex:degreeSource ?o2 .
}
""")
sparql.setReturnFormat(JSON)
sparql.setMethod(GET)
results = sparql.query().convert()
for result in results["results"]["bindings"]:
print(result["o2"]["value"])
#Insert Sergio
sparql.setQuery("""
PREFIX ex: <http://example.org/>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
INSERT DATA {
ex:Sergio a foaf:Person ;
ex:address [ a ex:Address ;
ex:city ex:Valenciay ;
ex:country ex:Spain ;
ex:postalCode "46021"^^xsd:string ;
ex:state ex:California ;
ex:street "4_Carrer_del_Serpis"^^xsd:string ] ;
ex:degree [ ex:degreeField ex:Computer_science ;
ex:degreeLevel "Master"^^xsd:string ;
ex:degreeSource ex:University_of_Valencia ;
ex:year "2008"^^xsd:gYear ] ;
ex:expertise ex:Big_data,
ex:Semantic_technologies,
ex:Machine_learning;
foaf:name "Sergio_Pastor"^^xsd:string .
}
""")
sparql.setMethod(POST)
results = sparql.query()
print(results.response.read())
sparql.setMethod(GET)
# Describe Sergio
sparql.setReturnFormat(TURTLE)
sparql.setQuery("""
PREFIX ex: <http://example.org/>
DESCRIBE ex:Sergio ?o
WHERE {
ex:Sergio ?p ?o .
?o ?p2 ?o2 .
}
""")
results = sparql.query().convert()
print(results.serialize(format='turtle'))
# Construct that any city is in the country in an address
sparql.setQuery("""
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX ex: <http://example.org/>
CONSTRUCT {?city ex:locatedIn ?country}
Where {
?s rdf:type ex:Address .
?s ex:city ?city .
?s ex:country ?country.
}
""")
sparql.setReturnFormat(TURTLE)
results = sparql.query().convert()
print(results.serialize(format='turtle'))
Web APIs and JSON-LD
import requests
from rdflib import FOAF, Namespace, Literal, RDF, Graph, TURTLE
r = requests.get('http://api.open-notify.org/astros.json').json()
g = Graph()
EX = Namespace('http://EXample.org/')
g.bind("ex", EX)
for item in r['people']:
craft = item['craft'].replace(" ","_")
person = item['name'].replace(" ","_")
g.add((EX[person], EX.onCraft, EX[craft]))
g.add((EX[person], RDF.type, FOAF.Person))
g.add((EX[person], FOAF.name, Literal(item['name'])))
g.add((EX[craft], FOAF.name, Literal(item['craft'])))
res = g.query("""
CONSTRUCT {?person1 foaf:knows ?person2}
WHERE {
?person1 ex:onCraft ?craft .
?person2 ex:onCraft ?craft .
}
""")
for triplet in res:
# (we don't need to add that they know themselves)
if (triplet[0] != triplet[2]):
g.add((triplet))
print(g.serialize(format="turtle"))
Semantic lifting - CSV
import pandas as pd
from rdflib import Graph, Namespace, URIRef, Literal
from rdflib.namespace import RDF, XSD
ex = Namespace("http://example.org/")
dbr = Namespace("http://dbpedia.org/resource/")
dbp = Namespace("https://dbpedia.org/property/")
dbpage = Namespace("https://dbpedia.org/page/")
sem = Namespace("http://semanticweb.cs.vu.nl/2009/11/sem/")
tl = Namespace("http://purl.org/NET/c4dm/timeline.owl#")
g = Graph()
g.bind("ex", ex)
g.bind("dbr", dbr)
g.bind("dbp", dbp)
g.bind("dbpage", dbpage)
g.bind("sem", sem)
g.bind("tl", tl)
df = pd.read_csv("russia-investigations.csv")
# We need to correct the type of the columns in the DataFrame, as Pandas assigns an incorrect type when it reads the file (for me at least). We use .astype("str") to convert the content of the columns to a string.
df["name"] = df["name"].astype("str")
df["type"] = df["type"].astype("str")
# iterrows creates an iterable object (list of rows)
for index, row in df.iterrows():
investigation = URIRef(ex + row['investigation'])
investigation_start = Literal(row['investigation-start'], datatype=XSD.date)
investigation_end = Literal(row['investigation-end'], datatype=XSD.date)
investigation_days = Literal(row['investigation-days'], datatype=XSD.integer)
name = Literal(row['name'], datatype=XSD.string)
name_underscore = URIRef(dbpage + row['name'].replace(" ","_"))
investigation_result = URIRef(ex + row['investigation']+ "_investigation_" + row['name'].replace(" ","_"))
indictment_days = Literal(row['indictment-days'], datatype=XSD.integer)
type = URIRef(dbr + row['type'].replace(" ","_"))
cp_date = Literal(row['cp-date'], datatype=XSD.date)
cp_days = Literal(row['cp-days'], datatype=XSD.duration)
overturned = Literal(row['overturned'], datatype=XSD.boolean)
pardoned = Literal(row['pardoned'], datatype=XSD.boolean)
american = Literal(row['american'], datatype=XSD.boolean)
president = Literal(row['president'], datatype=XSD.string)
president_underscore = URIRef(dbr + row['president'].replace(" ","_"))
g.add((investigation, RDF.type, sem.Event))
g.add((investigation, sem.hasBeginTimeStamp, investigation_start))
g.add((investigation, sem.hasEndTimeStamp, investigation_end))
g.add((investigation, tl.duration, investigation_days))
g.add((investigation, dbp.president, president_underscore))
g.add((investigation, sem.hasSubEvent, investigation_result))
g.add((investigation_result, ex.resultType, type))
g.add((investigation_result, ex.objectOfInvestigation, name_underscore))
g.add((investigation_result, ex.isAmerican, american))
g.add((investigation_result, ex.indictmentDuration, indictment_days))
g.add((investigation_result, ex.caseSolved, cp_date))
g.add((investigation_result, ex.daysBeforeCaseSolved, cp_days))
g.add((investigation_result, ex.overturned, overturned))
g.add((investigation_result, ex.pardoned, pardoned))
g.serialize("output.ttl",format="ttl")
RDFS
from rdflib.namespace import RDF, FOAF, XSD, RDFS
from rdflib import OWL, Graph, Namespace, URIRef, Literal, BNode
from rdflib.namespace import RDF, RDFS, XSD, OWL
import owlrl
ex = Namespace("http://example.org/")
dbr = Namespace("http://dbpedia.org/resource/")
dbp = Namespace("https://dbpedia.org/property/")
dbpage = Namespace("https://dbpedia.org/page/")
sem = Namespace("http://semanticweb.cs.vu.nl/2009/11/sem/")
tl = Namespace("http://purl.org/NET/c4dm/timeline.owl#")
g = Graph()
g.bind("ex", ex)
g.bind("dbr", dbr)
g.bind("dbp", dbp)
g.bind("dbpage", dbpage)
g.bind("sem", sem)
g.bind("tl", tl)
g.parse(location="exampleTTL.ttl", format="turtle")
# University of California and University of Valencia are both Universities.
g.add((ex.University_of_California, RDF.type, ex.University))
g.add((ex.University_of_Valencia, RDF.type, ex.University))
# All universities are higher education institutions (HEIs).
g.add((ex.University, RDFS.subClassOf, ex.Higher_education))
# Only persons can have an expertise, and what they have expertise in is always a subject.
g.add((ex.expertise, RDFS.domain, FOAF.Person))
g.add((ex.expertise, RDFS.range, ex.subject))
# Only persons can graduate from a HEI.
g.add((ex.graduatedFromHEI, RDFS.domain, FOAF.Person))
g.add((ex.graduatedFromHEI, RDFS.range, ex.Higher_education))
# If you are a student, you are in fact a person as well.
g.add((ex.Student, RDFS.subClassOf, FOAF.Person))
# That a person is married to someone, means that they know them.
g.add((ex.married, RDFS.subPropertyOf, FOAF.knows))
# Finally, if a person has a name, that name is also the label of that entity."
g.add((FOAF.name, RDFS.subPropertyOf, RDFS.label))
# Having a degree from a HEI means that you have also graduated from that HEI.
g.add((ex.graduatedFromHEI, RDFS.subPropertyOf, ex.degree))
# That a city is a capital of a country means that this city is located in that country.
g.add((ex.capital, RDFS.domain, ex.Country))
g.add((ex.capital, RDFS.range, ex.City))
g.add((ex.capital, RDFS.subPropertyOf, ex.hasLocation))
# That someone was involved in a meeting, means that they have met the other participants.
# This question was bad for the RDFS lab because we need complex OWL or easy sparql.
res = g.query("""
CONSTRUCT {?person1 ex:haveMet ?person2}
WHERE {
?person1 ex:meeting ?Meeting .
?Meeting ex:involved ?person2 .
}
""")
for triplet in res:
#we don't need to add that people have met themselves
if (triplet[0] != triplet[2]):
g.add((triplet))
# If someone partook in a meeting somewhere, means that they have visited that place"
# This question was bad for the RDFS lab for the same reason.
res = g.query("""
CONSTRUCT {?person ex:hasVisited ?place}
WHERE {
?person1 ex:meeting ?Meeting .
?Meeting ex:location ?place .
}
""")
for triplet in res:
g.add((triplet))
rdfs = owlrl.OWLRL.OWLRL_Semantics(g, False, False, False)
rdfs.closure()
rdfs.flush_stored_triples()
g.serialize("output.ttl",format="ttl")
More miscellaneous examples
Printing the triples of the Graph in a readable way
# The turtle format has the purpose of being more readable for humans.
print(g.serialize(format="turtle"))
Coding Tasks Lab 1
from rdflib import Graph, Namespace, URIRef, BNode, Literal
from rdflib.namespace import RDF, FOAF, XSD
g = Graph()
ex = Namespace("http://example.org/")
g.add((ex.Cade, ex.married, ex.Mary))
g.add((ex.France, ex.capital, ex.Paris))
g.add((ex.Cade, ex.age, Literal("27", datatype=XSD.integer)))
g.add((ex.Mary, ex.age, Literal("26", datatype=XSD.integer)))
g.add((ex.Mary, ex.interest, ex.Hiking))
g.add((ex.Mary, ex.interest, ex.Chocolate))
g.add((ex.Mary, ex.interest, ex.Biology))
g.add((ex.Mary, RDF.type, ex.Student))
g.add((ex.Paris, RDF.type, ex.City))
g.add((ex.Paris, ex.locatedIn, ex.France))
g.add((ex.Cade, ex.characteristic, ex.Kind))
g.add((ex.Mary, ex.characteristic, ex.Kind))
g.add((ex.Mary, RDF.type, FOAF.Person))
g.add((ex.Cade, RDF.type, FOAF.Person))
# OR
g = Graph()
ex = Namespace('http://example.org/')
g.add((ex.Cade, FOAF.name, Literal("Cade", datatype=XSD.string)))
g.add((ex.Mary, FOAF.name, Literal("Mary", datatype=XSD.string)))
g.add((ex.Cade, RDF.type, FOAF.Person))
g.add((ex.Mary, RDF.type, FOAF.Person))
g.add((ex.Mary, RDF.type, ex.Student))
g.add((ex.Cade, ex.Married, ex.Mary))
g.add((ex.Cade, FOAF.age, Literal('27', datatype=XSD.int)))
g.add((ex.Mary, FOAF.age, Literal('26', datatype=XSD.int)))
g.add((ex.Paris, RDF.type, ex.City))
g.add((ex.France, ex.Capital, ex.Paris))
g.add((ex.Mary, FOAF.interest, ex.hiking))
g.add((ex.Mary, FOAF.interest, ex.Chocolate))
g.add((ex.Mary, FOAF.interest, ex.biology))
g.add((ex.France, ex.City, ex.Paris))
g.add((ex.Mary, ex.characteristic, ex.kind))
g.add((ex.Cade, ex.characteristic, ex.kind))
g.add((ex.France, RDF.type, ex.Country))
print(g.serialize(format="turtle"))
Basic RDF programming
Different ways to create an address
from rdflib import Graph, Namespace, URIRef, BNode, Literal
from rdflib.namespace import RDF, FOAF, XSD
g = Graph()
ex = Namespace("http://example.org/")
# How to represent the address of Cade Tracey. From probably the worst solution to the best.
# Solution 1 -
# Make the entire address into one Literal. However, Generally we want to separate each part of an address into their own triples. This is useful for instance if we want to find only the streets where people live.
g.add((ex.Cade_Tracey, ex.livesIn, Literal("1516_Henry_Street, Berkeley, California 94709, USA")))
# Solution 2 -
# Seperate the different pieces information into their own triples
g.add((ex.Cade_tracey, ex.street, Literal("1516_Henry_Street")))
g.add((ex.Cade_tracey, ex.city, Literal("Berkeley")))
g.add((ex.Cade_tracey, ex.state, Literal("California")))
g.add((ex.Cade_tracey, ex.zipcode, Literal("94709")))
g.add((ex.Cade_tracey, ex.country, Literal("USA")))
# Solution 3 - Some parts of the addresses can make more sense to be resources than Literals.
# Larger concepts like a city or state are typically represented as resources rather than Literals, but this is not necesarilly a requirement in the case that you don't intend to say more about them.
g.add((ex.Cade_tracey, ex.street, Literal("1516_Henry_Street")))
g.add((ex.Cade_tracey, ex.city, ex.Berkeley))
g.add((ex.Cade_tracey, ex.state, ex.California))
g.add((ex.Cade_tracey, ex.zipcode, Literal("94709")))
g.add((ex.Cade_tracey, ex.country, ex.USA))
# Solution 4
# Grouping of the information into an Address. We can Represent the address concept with its own URI OR with a Blank Node.
# One advantage of this is that we can easily remove the entire address, instead of removing each individual part of the address.
# Solution 4 or 5 is how I would recommend to make addresses. Here, ex.CadeAddress could also be called something like ex.address1 or so on, if you want to give each address a unique ID.
# Address URI - CadeAdress
g.add((ex.Cade_Tracey, ex.address, ex.CadeAddress))
g.add((ex.CadeAddress, RDF.type, ex.Address))
g.add((ex.CadeAddress, ex.street, Literal("1516 Henry Street")))
g.add((ex.CadeAddress, ex.city, ex.Berkeley))
g.add((ex.CadeAddress, ex.state, ex.California))
g.add((ex.CadeAddress, ex.postalCode, Literal("94709")))
g.add((ex.CadeAddress, ex.country, ex.USA))
# OR
# Blank node for Address.
address = BNode()
g.add((ex.Cade_Tracey, ex.address, address))
g.add((address, RDF.type, ex.Address))
g.add((address, ex.street, Literal("1516 Henry Street", datatype=XSD.string)))
g.add((address, ex.city, ex.Berkeley))
g.add((address, ex.state, ex.California))
g.add((address, ex.postalCode, Literal("94709", datatype=XSD.string)))
g.add((address, ex.country, ex.USA))
# Solution 5 using existing vocabularies for address
# (in this case https://schema.org/PostalAddress from schema.org).
# Also using existing ontology for places like California. (like http://dbpedia.org/resource/California from dbpedia.org)
schema = Namespace("https://schema.org/")
dbp = Namespace("https://dpbedia.org/resource/")
g.add((ex.Cade_Tracey, schema.address, ex.CadeAddress))
g.add((ex.CadeAddress, RDF.type, schema.PostalAddress))
g.add((ex.CadeAddress, schema.streetAddress, Literal("1516 Henry Street")))
g.add((ex.CadeAddress, schema.addresCity, dbp.Berkeley))
g.add((ex.CadeAddress, schema.addressRegion, dbp.California))
g.add((ex.CadeAddress, schema.postalCode, Literal("94709")))
g.add((ex.CadeAddress, schema.addressCountry, dbp.United_States))
Typed Literals
from rdflib import Graph, Literal, Namespace
from rdflib.namespace import XSD
g = Graph()
ex = Namespace("http://example.org/")
g.add((ex.Cade, ex.age, Literal(27, datatype=XSD.integer)))
g.add((ex.Cade, ex.gpa, Literal(3.3, datatype=XSD.float)))
g.add((ex.Cade, FOAF.name, Literal("Cade Tracey", datatype=XSD.string)))
g.add((ex.Cade, ex.birthday, Literal("2006-01-01", datatype=XSD.date)))
Writing and reading graphs/files
# Writing the graph to a file on your system. Possible formats = turtle, n3, xml, nt.
g.serialize(destination="triples.txt", format="turtle")
# Parsing a local file
parsed_graph = g.parse(location="triples.txt", format="turtle")
# Parsing a remote endpoint like Dbpedia
dbpedia_graph = g.parse("http://dbpedia.org/resource/Pluto")
Graph Binding
#Graph Binding is useful for at least two reasons:
#(1) We no longer need to specify prefixes with SPARQL queries if they are already binded to the graph.
#(2) When serializing the graph, the serialization will show the correct expected prefix
# instead of default namespace names ns1, ns2 etc.
g = Graph()
ex = Namespace("http://example.org/")
dbp = Namespace("http://dbpedia.org/resource/")
schema = Namespace("https://schema.org/")
g.bind("ex", ex)
g.bind("dbp", dbp)
g.bind("schema", schema)
Collection Example
from rdflib import Graph, Namespace
from rdflib.collection import Collection
# Sometimes we want to add many objects or subjects for the same predicate at once.
# In these cases we can use Collection() to save some time.
# In this case I want to add all countries that Emma has visited at once.
b = BNode()
g.add((ex.Emma, ex.visit, b))
Collection(g, b,
[ex.Portugal, ex.Italy, ex.France, ex.Germany, ex.Denmark, ex.Sweden])
# OR
g.add((ex.Emma, ex.visit, ex.EmmaVisits))
Collection(g, ex.EmmaVisits,
[ex.Portugal, ex.Italy, ex.France, ex.Germany, ex.Denmark, ex.Sweden])
SPARQL
Also see the SPARQL Examples page!
Querying a local ("in memory") graph
Example contents of the file family.ttl:
@prefix rex: <http://example.org/royal#> . @prefix fam: <http://example.org/family#> . rex:IngridAlexandra fam:hasParent rex:HaakonMagnus . rex:SverreMagnus fam:hasParent rex:HaakonMagnus . rex:HaakonMagnus fam:hasParent rex:Harald . rex:MarthaLouise fam:hasParent rex:Harald . rex:HaakonMagnus fam:hasSister rex:MarthaLouise .
import rdflib g = rdflib.Graph() g.parse("family.ttl", format='ttl') qres = g.query(""" PREFIX fam: <http://example.org/family#> SELECT ?child ?sister WHERE { ?child fam:hasParent ?parent . ?parent fam:hasSister ?sister . }""") for row in qres: print("%s has aunt %s" % row)
With a prepared query, you can write the query once, and then bind some of the variables each time you use it:
import rdflib g = rdflib.Graph() g.parse("family.ttl", format='ttl') q = rdflib.plugins.sparql.prepareQuery( """SELECT ?child ?sister WHERE { ?child fam:hasParent ?parent . ?parent fam:hasSister ?sister . }""", initNs = { "fam": "http://example.org/family#"}) sm = rdflib.URIRef("http://example.org/royal#SverreMagnus") for row in g.query(q, initBindings={'child': sm}): print(row)
Select all contents of lists (rdfllib.Collection)
# rdflib.Collection has a different interntal structure so it requires a slightly more advance query. Here I am selecting all places that Emma has visited.
PREFIX ex: <http://example.org/>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
SELECT ?visit
WHERE {
ex:Emma ex:visit/rdf:rest*/rdf:first ?visit
}
Using parameters/variables in rdflib queries
from rdflib import Graph, Namespace, URIRef
from rdflib.plugins.sparql import prepareQuery
g = Graph()
ex = Namespace("http://example.org/")
g.bind("ex", ex)
g.add((ex.Cade, ex.livesIn, ex.France))
g.add((ex.Anne, ex.livesIn, ex.Norway))
g.add((ex.Sofie, ex.livesIn, ex.Sweden))
g.add((ex.Per, ex.livesIn, ex.Norway))
g.add((ex.John, ex.livesIn, ex.USA))
def find_people_from_country(country):
country = URIRef(ex + country)
q = prepareQuery(
"""
PREFIX ex: <http://example.org/>
SELECT ?person WHERE {
?person ex:livesIn ?country.
}
""")
capital_result = g.query(q, initBindings={'country': country})
for row in capital_result:
print(row)
find_people_from_country("Norway")
SELECTING data from Blazegraph via Python
from SPARQLWrapper import SPARQLWrapper, JSON
# This creates a server connection to the same URL that contains the graphic interface for Blazegraph.
# You also need to add "sparql" to end of the URL like below.
sparql = SPARQLWrapper("http://localhost:9999/blazegraph/sparql")
# SELECT all triples in the database.
sparql.setQuery("""
SELECT DISTINCT ?p WHERE {
?s ?p ?o.
}
""")
sparql.setReturnFormat(JSON)
results = sparql.query().convert()
for result in results["results"]["bindings"]:
print(result["p"]["value"])
# SELECT all interests of Cade
sparql.setQuery("""
PREFIX ex: <http://example.org/>
SELECT DISTINCT ?interest WHERE {
ex:Cade ex:interest ?interest.
}
""")
sparql.setReturnFormat(JSON)
results = sparql.query().convert()
for result in results["results"]["bindings"]:
print(result["interest"]["value"])
Updating data from Blazegraph via Python
from SPARQLWrapper import SPARQLWrapper, POST, DIGEST
namespace = "kb"
sparql = SPARQLWrapper("http://localhost:9999/blazegraph/namespace/"+ namespace + "/sparql")
sparql.setMethod(POST)
sparql.setQuery("""
PREFIX ex: <http://example.org/>
INSERT DATA{
ex:Cade ex:interest ex:Mathematics.
}
""")
results = sparql.query()
print(results.response.read())
Retrieving data from Wikidata with SparqlWrapper
from SPARQLWrapper import SPARQLWrapper, JSON
sparql = SPARQLWrapper("https://query.wikidata.org/sparql")
# In the query I want to select all the Vitamins in wikidata.
sparql.setQuery("""
SELECT ?nutrient ?nutrientLabel WHERE
{
?nutrient wdt:P279 wd:Q34956.
SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
}
""")
sparql.setReturnFormat(JSON)
results = sparql.query().convert()
for result in results["results"]["bindings"]:
print(result["nutrient"]["value"], " ", result["nutrientLabel"]["value"])
More examples can be found in the example section on the official query service here: https://query.wikidata.org/.
Download from BlazeGraph
"""
Dumps a database to a local RDF file.
You need to install the SPARQLWrapper package first...
"""
import datetime
from SPARQLWrapper import SPARQLWrapper, RDFXML
# your namespace, the default is 'kb'
ns = 'kb'
# the SPARQL endpoint
endpoint = 'http://info216.i2s.uib.no/bigdata/namespace/' + ns + '/sparql'
# - the endpoint just moved, the old one was:
# endpoint = 'http://i2s.uib.no:8888/bigdata/namespace/' + ns + '/sparql'
# create wrapper
wrapper = SPARQLWrapper(endpoint)
# prepare the SPARQL update
wrapper.setQuery('CONSTRUCT { ?s ?p ?o } WHERE { ?s ?p ?o }')
wrapper.setReturnFormat(RDFXML)
# execute the SPARQL update and convert the result to an rdflib.Graph
graph = wrapper.query().convert()
# the destination file, with code to make it timestamped
destfile = 'rdf_dumps/slr-kg4news-' + datetime.datetime.now().strftime('%Y%m%d-%H%M') + '.rdf'
# serialize the result to file
graph.serialize(destination=destfile, format='ttl')
# report and quit
print('Wrote %u triples to file %s .' %
(len(res), destfile))
Query Dbpedia with SparqlWrapper
from SPARQLWrapper import SPARQLWrapper, JSON
sparql = SPARQLWrapper("http://dbpedia.org/sparql")
sparql.setQuery("""
PREFIX dbr: <http://dbpedia.org/resource/>
PREFIX dbo: <http://dbpedia.org/ontology/>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT ?comment
WHERE {
dbr:Barack_Obama rdfs:comment ?comment.
FILTER (langMatches(lang(?comment),"en"))
}
""")
sparql.setReturnFormat(JSON)
results = sparql.query().convert()
for result in results["results"]["bindings"]:
print(result["comment"]["value"])
Lifting CSV to RDF
from rdflib import Graph, Literal, Namespace, URIRef
from rdflib.namespace import RDF, FOAF, RDFS, OWL
import pandas as pd
g = Graph()
ex = Namespace("http://example.org/")
g.bind("ex", ex)
# Load the CSV data as a pandas Dataframe.
csv_data = pd.read_csv("task1.csv")
# Here I deal with spaces (" ") in the data. I replace them with "_" so that URI's become valid.
csv_data = csv_data.replace(to_replace=" ", value="_", regex=True)
# Here I mark all missing/empty data as "unknown". This makes it easy to delete triples containing this later.
csv_data = csv_data.fillna("unknown")
# Loop through the CSV data, and then make RDF triples.
for index, row in csv_data.iterrows():
# The names of the people act as subjects.
subject = row['Name']
# Create triples: e.g. "Cade_Tracey - age - 27"
g.add((URIRef(ex + subject), URIRef(ex + "age"), Literal(row["Age"])))
g.add((URIRef(ex + subject), URIRef(ex + "married"), URIRef(ex + row["Spouse"])))
g.add((URIRef(ex + subject), URIRef(ex + "country"), URIRef(ex + row["Country"])))
# If We want can add additional RDF/RDFS/OWL information e.g
g.add((URIRef(ex + subject), RDF.type, FOAF.Person))
# I remove triples that I marked as unknown earlier.
g.remove((None, None, URIRef("http://example.org/unknown")))
# Clean printing of the graph.
print(g.serialize(format="turtle").decode())
CSV file for above example
"Name","Age","Spouse","Country"
"Cade Tracey","26","Mary Jackson","US"
"Bob Johnson","21","","Canada"
"Mary Jackson","25","","France"
"Phil Philips","32","Catherine Smith","Japan"
Coding Tasks Lab 6
import pandas as pd
from rdflib import Graph, Namespace, URIRef, Literal, BNode
from rdflib.namespace import RDF, XSD
ex = Namespace("http://example.org/")
sem = Namespace("http://semanticweb.cs.vu.nl/2009/11/sem/")
g = Graph()
g.bind("ex", ex)
g.bind("sem", sem)
# Removing unwanted characters
df = pd.read_csv('russia-investigation.csv')
# Here I deal with spaces (" ") in the data. I replace them with "_" so that URI's become valid.
df = df.replace(to_replace=" ", value="_", regex=True)
# This may seem odd, but in the data set we have a name like this:("Scooter"). So we have to remove quotation marks
df = df.replace(to_replace=f'"', value="", regex=True)
# # Here I mark all missing/empty data as "unknown". This makes it easy to delete triples containing this later.
df = df.fillna("unknown")
# Loop through the CSV data, and then make RDF triples.
for index, row in df.iterrows():
name = row['investigation']
investigation = URIRef(ex + name)
g.add((investigation, RDF.type, sem.Event))
investigation_start = row["investigation-start"]
g.add((investigation, sem.hasBeginTimeStamp, Literal(
investigation_start, datatype=XSD.datetime)))
investigation_end = row["investigation-end"]
g.add((investigation, sem.hasEndTimeStamp, Literal(
investigation_end, datatype=XSD.datetime)))
investigation_end = row["investigation-days"]
g.add((investigation, sem.hasXSDDuration, Literal(
investigation_end, datatype=XSD.Days)))
person = row["name"]
person = URIRef(ex + person)
g.add((investigation, sem.Actor, person))
result = row['type']
g.add((investigation, sem.hasSubEvent, Literal(result, datatype=XSD.string)))
overturned = row["overturned"]
g.add((investigation, ex.overtuned, Literal(overturned, datatype=XSD.boolean)))
pardoned = row["pardoned"]
g.add((investigation, ex.pardon, Literal(pardoned, datatype=XSD.boolean)))
g.serialize("output.ttl", format="ttl")
print(g.serialize(format="turtle"))