Semantic Web Practice - simple SPARQL example in Protege

Suppose that you have your personal profile ontology as displayed below, and the individual -> guangyuan-piao has data type properties:

  • guangyuan-piao→foaf:age→28
  • guangyuan-piao→foaf:familyName→"Piao"
  • guangyuan-piao→foaf:givenName→"Guangyuan"

Practice#1 : select organizations and persons which has the relationship "member".

 1:  PREFIX foaf: <http://xmlns.com/foaf/0.1/>  
 2:  SELECT ?organization ?person  
 3:     WHERE { ?organization foaf:member ?person }  

This  should return all organization-person pairs with the relationship "member". The query result is as below:
  • DERI - guangyuan-piao
  • Yonsei_Univeristy - guangyuan-piao
  • Jilin_University - guangyuan-piao

Practice#2 : select person with his/her age who has family name "piao".

1:  PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>  
2:  PREFIX foaf: <http://xmlns.com/foaf/0.1/>  
3:  SELECT ?person ?age  
4:       WHERE { ?person foaf:age ?age .  
5:               ?person foaf:familyName "Piao"^^xsd:string  
6:       }  

Practice#3 : select full name who at the age of 28.

1:  PREFIX foaf: <http://xmlns.com/foaf/0.1/>  
2:  SELECT ( CONCAT(?G," ",?F) AS ?name)  
3:       WHERE { ?P foaf:givenName ?G; foaf:familyName ?F .  
4:               ?P foaf:age 28  
5:       }  

Practice#4 : select person who's family name start with "Pi".


1:  PREFIX foaf: <http://xmlns.com/foaf/0.1/>  
2:  SELECT ?person  
3:      WHERE { ?person foaf:familyName ?fn .  
4:              FILTER regex(?fn, "^Pi")   
5:      }  

Q: What if change the regex(?fn, "^Pi") to regex(?fn, "^pi")?
A: It will not return any value since it's case-sensitive. But you could give the case-insensitive option to get the result.

1:  PREFIX foaf: <http://xmlns.com/foaf/0.1/>  
2:  SELECT ?person  
3:      WHERE { ?person foaf:familyName ?fn .  
4:          FILTER regex(?fn, "^pi", "i")   
5:      }  

Practice#5 : select person who's age is over 29.

1:  PREFIX foaf: <http://xmlns.com/foaf/0.1/>  
2:  SELECT ?person  
3:      WHERE { ?person foaf:age ?age .  
4:          FILTER (?age > 29)   
5:      }  

There's none of the result since guangyuan-piao's age is 28.

Practice#6 : select individual who has Person class.

1:  PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>  
2:  PREFIX foaf: <http://xmlns.com/foaf/0.1/>  
3:  SELECT ?person  
4:       WHERE { ?person rdf:type foaf:Person }  

This is an easy SPARQL and SPARQL also provide keyword "a" which is alternative for IRI-http://www.w3.org/1999/02/22-rdf-syntax-ns#type (case sensitive) looks neat than before.

1:  PREFIX foaf: <http://xmlns.com/foaf/0.1/>  
2:  SELECT ?person  
3:       WHERE { ?person a foaf:Person }  



Other Examples:

# Example: Select all MusicArtists and Bands from DBpedia
# Example: How to query SPARQL with spaces? 

No comments:

Post a Comment