Henriette's Notes

Home » 2018 » June

Monthly Archives: June 2018

Getting started with Ontotext GraphDB and Jena

In my previous post I explained how you can create an GraphDB repository and how you can update and query your repository using RDF4J. In this post I provide an example of how you can update and query a GraphDB repository using Jena. However, even though the code works, there are some pitfalls.

A Quick Example

First you need to add Jena as a Maven dependency:

<dependency>
 <groupId>org.apache.jena</groupId>
 <artifactId>apache-jena-libs</artifactId>
 <version>3.7.0</version>
 <type>pom</type>
</dependency>  

The Java code is straightforward:

package org.graphdb.jena.tutorial;

import org.apache.jena.query.QueryExecution;
import org.apache.jena.query.QueryExecutionFactory;
import org.apache.jena.query.QuerySolution;
import org.apache.jena.query.ResultSet;
import org.apache.jena.update.UpdateExecutionFactory;
import org.apache.jena.update.UpdateFactory;
import org.apache.jena.update.UpdateProcessor;
import org.apache.jena.update.UpdateRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.Marker;
import org.slf4j.MarkerFactory;

public class SimpleInsertQueryExample {
  private static Logger logger = LoggerFactory.getLogger(SimpleInsertQueryExample.class);
  // Why This Failure marker
  private static final Marker WTF_MARKER = MarkerFactory.getMarker("WTF");
  
  // GraphDB 
  private static final String PERSONDATA_REPO_QUERY = 
      "http://localhost:7200/repositories/PersonData";
  private static final String PERSONDATA_REPO_UPDATE = 
      "http://localhost:7200/repositories/PersonData/statements";


  private static String strInsert;
  private static String strQuery;
  
  static {
    strInsert = 
        "INSERT DATA {"
         + "<http://dbpedia.org/resource/Grace_Hopper> "
         + "<http://dbpedia.org/ontology/birthDate>"
         + " \"1906-12-09\"^^<http://www.w3.org/2001/XMLSchema#date> ."
         + "<http://dbpedia.org/resource/Grace_Hopper> "
         + "<http://dbpedia.org/ontology/birthPlace> "
         + "<http://dbpedia.org/resource/New_York_City> ."
         + "<http://dbpedia.org/resource/Grace_Hopper> "
         + "<http://dbpedia.org/ontology/deathDate>"
         + " \"1992-01-01\"^^<http://www.w3.org/2001/XMLSchema#date> ."
         + "<http://dbpedia.org/resource/Grace_Hopper> "
         + "<http://dbpedia.org/ontology/deathPlace> "
         + "<http://dbpedia.org/resource/Arlington_County,_Virginia> ."
         + "<http://dbpedia.org/resource/Grace_Hopper> "
         + "<http://purl.org/dc/terms/description>"
         + " \"American computer scientist and United States Navy officer.\" ."
         + "<http://dbpedia.org/resource/Grace_Hopper> "
         + "<http://www.w3.org/1999/02/22-rdf-syntax-ns#type> "
         + "<http://dbpedia.org/ontology/Person> ."
         + "<http://dbpedia.org/resource/Grace_Hopper> "
         + "<http://xmlns.com/foaf/0.1/gender> \"female\" ."
         + "<http://dbpedia.org/resource/Grace_Hopper> "
         + "<http://xmlns.com/foaf/0.1/givenName> \"Grace\" ."
         + "<http://dbpedia.org/resource/Grace_Hopper> "
         + "<http://xmlns.com/foaf/0.1/name> \"Grace Hopper\" ."
         + "<http://dbpedia.org/resource/Grace_Hopper>"
         + " <http://xmlns.com/foaf/0.1/surname> \"Hopper\" ."        
         + "}";
    
    strQuery = 
        "SELECT ?name WHERE {?s <http://xmlns.com/foaf/0.1/name> ?name .}";
  }   
  
  private static void insert() {
    UpdateRequest updateRequest = UpdateFactory.create(strInsert);
    UpdateProcessor updateProcessor = UpdateExecutionFactory
        .createRemote(updateRequest, 
        PERSONDATA_REPO_UPDATE);
    updateProcessor.execute();
  }
  
  private static void query() {
    QueryExecution queryExecution = QueryExecutionFactory
        .sparqlService(PERSONDATA_REPO_QUERY, strQuery);
    for (ResultSet results = queryExecution.execSelect(); results.hasNext();) {
      QuerySolution qs = results.next();
      String strName = qs.get("?name").toString();
      logger.trace("name = " + strName);
    }    
    queryExecution.close();
  }

  
  public static void main(String[] args) {
    try {
      insert(); 
      query();      
    } catch (Throwable t) {
      logger.error(WTF_MARKER, t.getMessage(), t);
    }   
  }  
}

Some Pitfalls

The example I provided will insert RDF data into GraphDB and query it successfully. However, the data is inserted into the repository in the absence of a transaction. The transaction API of Jena is based on a Dataset. Historically Ontotext provided a Jena adapter with which a Jena Dataset could be created. However, based on my question on Stack Overflow in this regard, the Jena adapter is no longer supported by Ontotext. Hence, currently it is not clear to me how to enable transactions when using Jena to access GraphDB. So, if you know how to address this, please be so kind as to leave a comment with your insight!

Conclusion

In this post I provided a quick example of how you can access GraphDB using Jena. However, this example does not support transactions, and therefore you may want to look at rather using RDF4J with GraphDB. You can find this code at github.

Getting started with Ontotext GraphDB and RDF4J

In this post I will explain how to quickly get started with the free version of Ontotext GraphDB and RDF4J. Ontotext GraphDB is an RDF datastore and RDF4J is a Java framework for accessing RDF datastores (not just GraphDB). I will explain

  1. how to install and start GraphDB, as well as how to use the workbench to add a repository, and
  2. how to do SPARQL queries against GraphDB using RDF4J.

Install and start GraphDB and create a Repository

To gain access to the free version of GraphDB you have to email Ontotext. They will respond with an email with links to a desktop and stand-alone server version of GraphDB. You want to download the stand-alone server version. This is a graphdb-free-VERSION-dist.zip file, that you can extract somewhere on your filesystem, which I will refer to here as $GRAPHDB_ROOT. To start GraphDB, go to $GRAPHDB_ROOT/bin and run ./graphdb.

To access the workbench you can go to http://localhost:7200. To create a new repository, in the left-hand side menu navigate to Setup>Repositories. Click the Create new repository button. For our simple example we will use PersonData as an Repository ID. The rest of the settings we leave as-is. At the bottom of the page you can press the Create button.

Accessing a GraphDB Repository using RDF4J

To access our PersonData repository we will use RDF4J. Since GraphDB is based on the RDF4J libraries, we only need to include the GraphDB dependencies since these already include RDF4J. Thus, in our pom.xml file we only need to add the following:

 <dependency>
   <groupId>com.ontotext.graphdb</groupId>
   <artifactId>graphdb-free-runtime</artifactId>
   <version>8.5.0</version>
 </dependency>

In our example Java code we first insert some RDF data and then do a query based on the added data. For inserting data we start a transaction and commit it, or, if it fails we do a rollback. For querying the data we iterate through the TupleQueryResult, retrieving values for the binding variables we are interested in (i.e. name in this case). In line with the TupleQueryResult documentation, we close the TupleQueryResult once we are done.

package org.graphdb.rdf4j.tutorial;
package org.graphdb.rdf4j.tutorial;

import org.eclipse.rdf4j.model.impl.SimpleLiteral;
import org.eclipse.rdf4j.query.BindingSet;
import org.eclipse.rdf4j.query.QueryEvaluationException;
import org.eclipse.rdf4j.query.QueryLanguage;
import org.eclipse.rdf4j.query.TupleQuery;
import org.eclipse.rdf4j.query.TupleQueryResult;
import org.eclipse.rdf4j.query.Update;
import org.eclipse.rdf4j.repository.Repository;
import org.eclipse.rdf4j.repository.RepositoryConnection;
import org.eclipse.rdf4j.repository.http.HTTPRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.Marker;
import org.slf4j.MarkerFactory;

public class SimpleInsertQueryExample {
  private static Logger logger = 
    LoggerFactory.getLogger(SimpleInsertQueryExample.class);
  // Why This Failure marker
  private static final Marker WTF_MARKER = 
    MarkerFactory.getMarker("WTF");
  
  // GraphDB 
  private static final String GRAPHDB_SERVER = 
    "http://localhost:7200/";
  private static final String REPOSITORY_ID = "PersonData";

  private static String strInsert;
  private static String strQuery;
  
  static {
    strInsert = 
        "INSERT DATA {"
         + "<http://dbpedia.org/resource/Grace_Hopper> <http://dbpedia.org/ontology/birthDate> \"1906-12-09\"^^<http://www.w3.org/2001/XMLSchema#date> ."
         + "<http://dbpedia.org/resource/Grace_Hopper> <http://dbpedia.org/ontology/birthPlace> <http://dbpedia.org/resource/New_York_City> ."
         + "<http://dbpedia.org/resource/Grace_Hopper> <http://dbpedia.org/ontology/deathDate> \"1992-01-01\"^^<http://www.w3.org/2001/XMLSchema#date> ."
         + "<http://dbpedia.org/resource/Grace_Hopper> <http://dbpedia.org/ontology/deathPlace> <http://dbpedia.org/resource/Arlington_County,_Virginia> ."
         + "<http://dbpedia.org/resource/Grace_Hopper> <http://purl.org/dc/terms/description> \"American computer scientist and United States Navy officer.\" ."
         + "<http://dbpedia.org/resource/Grace_Hopper> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://dbpedia.org/ontology/Person> ."
         + "<http://dbpedia.org/resource/Grace_Hopper> <http://xmlns.com/foaf/0.1/gender> \"female\" ."
         + "<http://dbpedia.org/resource/Grace_Hopper> <http://xmlns.com/foaf/0.1/givenName> \"Grace\" ."
         + "<http://dbpedia.org/resource/Grace_Hopper> <http://xmlns.com/foaf/0.1/name> \"Grace Hopper\" ."
         + "<http://dbpedia.org/resource/Grace_Hopper> <http://xmlns.com/foaf/0.1/surname> \"Hopper\" ."        
         + "}";
    
    strQuery = 
        "SELECT ?name FROM DEFAULT WHERE {" +
        "?s <http://xmlns.com/foaf/0.1/name> ?name .}";
  }  
  
  private static RepositoryConnection getRepositoryConnection() {
    Repository repository = new HTTPRepository(
      GRAPHDB_SERVER, REPOSITORY_ID);
    repository.initialize();
    RepositoryConnection repositoryConnection = 
      repository.getConnection();
    return repositoryConnection;
  }
  
  private static void insert(
    RepositoryConnection repositoryConnection) {
    
    repositoryConnection.begin();    
    Update updateOperation = repositoryConnection
      .prepareUpdate(QueryLanguage.SPARQL, strInsert);
    updateOperation.execute();
    
    try {
      repositoryConnection.commit();
    } catch (Exception e) {
      if (repositoryConnection.isActive())
        repositoryConnection.rollback();
    }
  }

  private static void query(
    RepositoryConnection repositoryConnection) {
    
    TupleQuery tupleQuery = repositoryConnection
      .prepareTupleQuery(QueryLanguage.SPARQL, strQuery);
    TupleQueryResult result = null;
    try {
      result = tupleQuery.evaluate();
      while (result.hasNext()) {
        BindingSet bindingSet = result.next();

        SimpleLiteral name = 
          (SimpleLiteral)bindingSet.getValue("name");
        logger.trace("name = " + name.stringValue());
      }
    }
    catch (QueryEvaluationException qee) {
      logger.error(WTF_MARKER, 
        qee.getStackTrace().toString(), qee);
    } finally {
      result.close();
    }    
  }  
  
  public static void main(String[] args) {
    RepositoryConnection repositoryConnection = null;
    try {   
      repositoryConnection = getRepositoryConnection();
      
      insert(repositoryConnection);
      query(repositoryConnection);      
      
    } catch (Throwable t) {
      logger.error(WTF_MARKER, t.getMessage(), t);
    } finally {
      repositoryConnection.close();
    }
  }  
}

Conclusion

In this brief post I gave a quick example of how you can setup a simple GraphDB repository and query it using SPARQL. You can find sample code on github.

A Common Misconception regarding OWL Properties

A misconception w.r.t. OWL properties that I come across from time-to-time is that people mistakenly think that properties express relations between classes rather than relations between individuals. In this post

  1. I explain how this misconception fails,
  2. I explain what is the meaning of OWL properties, and
  3. I explain how you can model relations between classes if that is really what you want to do.

Throughout this post I will refer to object properties only, even though what I say applies to data properties as well, except of course that object properties relate objects to objects whereas data properties relate objects to data type values.

As an example ontology I will use the following:

Class: Employer
Class: Employee

ObjectProperty: employs
   Domain: Employer
   Range: Employee

How thinking that Properties express Relations between Classes fails

Thinking that properties express relations between classes fails in two different ways:

  1. The first way in which the expectations of users fail under this misconception is that their assumption is that domain and range axioms behave as constraints. That is if we extend our Employer ontology with something nonsensical like
    Class: Cheese
    Class: Fridge
    
    Individual: companyFridge 
        Types: Fridge
        
    Individual: blueCheese
       Types: Cheese
       Facts: employs companyFridge
    

    the reasoner will indicate that our ontology is inconsistent because the individual blueCheese is not of type Employer and neither is the individual companyFridge an instance of Employee. However, this is not the case. This ontology is in fact consistent because domain and range axioms do not behave as constraints.

  2. The other way in which the assumption of users is shattered is that they tend to think that domain and range axioms mean that in our Employer ontology it means that instances of the Employer class must necessarily be linked via the employs property to an instance (or instances?) of Employee. Thus, the expectation is that if we have an instance Employer that is not linked to an instance of Employee via the employs property, the reasoner should give an inconsistency. Again, this is wrong. This ontology will still be consistent.

The Real Meaning of OWL Object Properties

The OWL specification is very explicit about the meaning of object properties. It states:

Object properties connect pairs of individuals.

So what is the meaning of domain and range axioms then? Domain and range axioms are not constraints to be checked, but rather they are axioms from which the reasoner can make inferences. What domain and range axioms state is that whenever two instances are linked via the employs property, for example, it means that the first instance is of type Employer and the second instance is of type Employee. Thus, in our cheese and fridge example, no matter how silly it is, the reasoner will infer that blueCheese is an instance of Employer and companyFridge is an instance of Employee.

Finally, the underlying mathematical formalization of object properties themselves does not enable linking of pairs of classes. An OWL object r is represented as a role r in description logics. Stating that the role r has the domain C and the range D, where C and D are concepts, is achieved through the following axioms:

DomainRangeAxiom whereTopis the set representing the application domain. An object property r between instances a and b is expressed as a role assertion
RoleAssertion in description logics. Note that this assertion contains no information regarding description logic concepts (i.e. classes in OWL).

If you really, really want to have a Link between Classes

So if you really, really want to express a relation between classes, how can this be done? For our Employer ontology we can state the following:

Class: Employer
   SubClassOf: employs some Employee

This states that the Employer class is a subclass of the class consisting of the instances that are linked to at least 1 instance of the Employee class. If we now have an instance of Employer that is not linked via employs to an instance of Employee, the reasoner will find that our ontology is inconsistent. To state that acme is an employer without employees, we state it as follows:

Individual: acme
   Types: Employer
   Facts: employs max 0 Employee

Conclusion

In this post I explained that object properties link individuals (not classes!) and that thinking otherwise can lead to various errors when designing an ontology.