RDF

Table of Contents

RDF

The main deal with an RDF is the Subject , Predicate , Object triples. This is what a RDF graph consists of.

Good explanation from the RDFlib documentation

RDF is a graph where the nodes are URI references, Blank Nodes or Literals, in RDFLib represented by the classes URIRef, BNode, and Literal. URIRefs and BNodes can both be thought of as resources, such a person, a company, a web-site, etc. A BNode is a node where the exact URI is not known. URIRefs are also used to represent the properties/predicates in the RDF graph. Literals represent attribute values, such as a name, a date, a number, etc.

Constructs

Classes

rdfs:Resource
the class of everything. All things described by RDF are resources.
rdfs:Class
declares a resource as a class for other resources
(no term)

Terminology

Internationlized Resource Identifier (IRI)
Unicode string that conforms to the syntax defined in RFC 3987
foaf
Fried on a friend relationship
Blank node
(also called bnode) is a node in an RDF graph representing a resource for which a URI or literal is not given.

SparQL

Pronounced "sparkle".

Query

Syntax

Most forms of SPARQL queries contain a set of triple patterns called basic graph pattern. Triple patterns are like RDF triples, except that each of the subject, predicate and object may be a variable. A basic graph pattern matches a subgraph of the RDF data when RDF terms from the subgraph may be substituted for the variables and the result is RDF graph equivalent to the subgraph.

Shorthands

  • a is shorthand for rdf:type

Simple query

Our dataset is:

<http://example.org/book/book1> <http://purl.org/dc/elements/1.1/title> "SPARQL Tutorial" .

I belive the . is just to "terminate" the triple.

Here we basically say the following: "Give me all triples where we have a book with a title."

SELECT ?title
WHERE
{
  <http://example.org/book/book1> <http://purl.org/dc/elements/1.1/title> ?title .
}

This query has one solution, or result:

title
"SPARQL Tutorial"

Real example using Python

from SPARQLWrapper import SPARQLWrapper, JSON

endpoint = "http://dbpedia.org/sparql"
q = """
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT ?label
WHERE { <http://dbpedia.org/resource/Asturias> rdfs:label ?label }
"""

sparql = SPARQLWrapper(endpoint)
sparql.setQuery(q)
sparql.setReturnFormat(JSON)

results = sparql.query().convert()

results

More complex query against DBPedia

One of the best resources for RDF graphs is DBPedia. To give a query a go, head over here and try the query below.

SELECT DISTINCT ?city ?country ?name ?lat ?long
WHERE {
  ?city a dbo:Place .
  ?city dbo:country ?country .
  ?city foaf:name ?name .
  ?city geo:lat ?lat .
  ?city geo:long ?long .
  FILTER (?country = :United_Kingdom) .
} ORDER BY ?name

Pretty neat, huh?