Search code examples
jsonsparqlamazon-neptune

Amazon Neptune SPARQL query through Java: Can I get the raw JSON response?


Docs for using the Java API for Amazon Neptune SPARQL SELECT queries only show how to iterate through the results of a TupleQuery. amazon docs

Is there a way to get the raw JSON response, so it's compatible with code that used to use the REST interface calls?


Solution

  • Like explained in the comments, the Java API just uses the JSON REST response and presents it to you as a TupleQueryResult object.

    If you wish to somehow receive raw JSON, you can just call the Neptune REST endpoint directly using any Java REST/HTTP client library.

    Alternatively, can also re-convert the result you get back through the Rdf4j API to JSON (or any other serialized format), as follows:

    public static void main( String[] args )
        {
            String sparqlEndpoint = "https://your-neptune-endpoint:port/sparql";
            Repository repo = new SPARQLRepository(sparqlEndpoint);
            repo.initialize();
    
            try (RepositoryConnection conn = repo.getConnection()) {
               String queryString = "SELECT ?s ?p ?o WHERE { ?s ?p ?o } limit 10";
    
               TupleQuery tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString);
    
               TupleQueryResultHandler jsonWriter = new SPARQLResultsJSONWriter(System.out);
               tupleQuery.evaluate(jsonWriter);
            }
        }
    

    Of course this is less efficient than using a REST client directly, as you're basically de-serializing and then immediately re-serializing the result, but it's a minimal code change if you're already using Rdf4j anyway.