Search code examples
javasparqlsesame

Export SPARQL query results into json file in sesame


I need to export SPARQL query results into JSON using Sesame. Should I use the class SPARQLResultsJSONWriter? How would this be implemented (in Java)?


Solution

  • This is actually explained in the Sesame Repository API user documentation, with code examples to demonstrate.

    However, to reiterate: once you have prepared a query by using RepositoryConnection.prepareTupleQuery, you can evaluate the returned TupleQuery object in two ways: one is by calling evaluate(), in which case the evaluation method will return a TupleQueryResult object. The other is by calling evaluate(TupleQueryResultHandler) and passing it a TupleQueryResultHandler instance, of which SPARQLResultJSONWriter is a subclass. So all you need to is bring the pieces together, like so:

    RepositoryConnection conn = rep.getConnection();
    try {
       // prepare the query
       String queryString = "SELECT * WHERE {?s ?p ?o . }";
       TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString);
    
       // open a file to write the result to it in JSON format
       OutputStream out = new FileOutputStream("/path/to/output.json");
       TupleQueryResultHandler writer = new SPARQLResultJSONWriter(out);
    
       // execute the query and write the result directly to file
       query.evaluate(writer);  
    }
    finally {
       conn.close();
    }