Jenarq

  sparql

Order

This article mainly shows how to use apache jena to SPARQL query RDF documents.

Relevant knowledge

RDF

The Resource Description Framework, a markup language used to describe Web resources. XML syntax and RDF Schema(RDFS) are used to describe metadata as a data model.

SPARQL

SPARQL (SPARQL Protocol and RDF Query Language) is a query language and data acquisition protocol developed for RDF. It is defined by the RDF data model developed by W3C, but it can be used for any information resource that can be represented by RDF.

Apache Jena

Jena is a Java toolbox for developing Web applications based on RDF and OWL semantics. It provides an rdfpi; ARP, an RDF parser; SPARQL, W3C RDF query language; An owlapi; And rules-based RDFS and OWL interface. ARQ is the SPARQL query engine in Jena.

Example

maven

        <dependency>
            <groupId>org.apache.jena</groupId>
            <artifactId>jena-core</artifactId>
            <version>3.7.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.jena</groupId>
            <artifactId>jena-arq</artifactId>
            <version>3.7.0</version>
        </dependency>

RDF documents

<?xml version="1.0"?>
<rdf:RDF
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:cd="http://www.example.com/cd#">

<rdf:Description
 rdf:about="http://www.example.com/cd/EmpireBurlesque">
  <cd:artist>Bob Dylan</cd:artist>
  <cd:country>USA</cd:country>
  <cd:company>Columbia</cd:company>
  <cd:price>10.90</cd:price>
  <cd:year>1985</cd:year>
</rdf:Description>

<rdf:Description
 rdf:about="http://www.example.com/cd/Hideyourheart">
  <cd:artist>Bonnie Tyler</cd:artist>
  <cd:country>UK</cd:country>
  <cd:company>CBS Records</cd:company>
  <cd:price>9.90</cd:price>
  <cd:year>1988</cd:year>
</rdf:Description>
</rdf:RDF>

SPARQL query

    @Test
    public void testJenaQuery(){
        Model model = ModelFactory.createDefaultModel();
        model.read(this.getClass().getClassLoader().getResourceAsStream("demo.rdf"), null);
        String queryString = "PREFIX cd: <http://www.example.com/cd#> \n " +
                "SELECT ?name where { ?item cd:artist ?name }";
        Query query = QueryFactory.create(queryString);
        QueryExecution qe = QueryExecutionFactory.create(query, model);
        ResultSet results = qe.execSelect();
        ResultSetFormatter.out(System.out, results, query);
    }

Output

------------------
| name           |
==================
| "Bonnie Tyler" |
| "Bob Dylan"    |
------------------

Summary

SPARQL is a query language for RDF, similar to SQL, but different, with a little learning cost, which needs further study.

doc