简体   繁体   中英

Retrieve items from a model in jena

I am running a query and saving the result into a JSON file. I am loading the json file as a model and trying to retrieve the list of subjects, objects and predicates. However I am getting the following error:

Exception in thread "main" org.apache.jena.riot.RiotException: [line: 2, col: 3 ] Relative IRI: head at org.apache.jena.riot.system.ErrorHandlerFactory$ErrorHandlerStd.error(ErrorHandlerFactory.java:128) at org.apache.jena.riot.checker.CheckerIRI.iriViolations(CheckerIRI.java:138) at org.apache.jena.riot.checker.CheckerIRI.iriViolations(CheckerIRI.java:100) at org.apache.jena.riot.system.ParserProfileChecker.makeIRI(ParserProfileChecker.java:66) at org.apache.jena.riot.system.ParserProfileChecker.resolveIRI(ParserProfileChecker.java:59) at org.apache.jena.riot.system.ParserProfileChecker.createURI(ParserProfileChecker.java:112) at org.apache.jena.riot.lang.LangRDFJSON.tryParseTriples(LangRDFJSON.java:121) at org.apache.jena.riot.lang.LangRDFJSON.tryParseGraph(LangRDFJSON.java:68) at org.apache.jena.riot.lang.LangRDFJSON.runParser(LangRDFJSON.java:56) at org.apache.jena.riot.lang.LangBase.parse(LangBase.java:42) at org.apache.jena.riot.RDFParserRegistry$ReaderRIOTLang.read(RDFParserRegi stry.java:176) at org.apache.jena.riot.RDFDataMgr.process(RDFDataMgr.java:861) at org.apache.jena.riot.RDFDataMgr.parse(RDFDataMgr.java:667) at org.apache.jena.riot.RDFDataMgr.read(RDFDataMgr.java:212) at org.apache.jena.riot.RDFDataMgr.read(RDFDataMgr.java:145) at org.apache.jena.riot.RDFDataMgr.read(RDFDataMgr.java:134) at org.apache.jena.riot.adapters.AdapterFileManager.readModelWorker(AdapterFileManager.java:282) at org.apache.jena.util.FileManager.loadModelWorker(FileManager.java:305) at org.apache.jena.util.FileManager.loadModel(FileManager.java:292) at Main.main(Main.java:51)

My code is:

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;

import org.apache.jena.query.Query;
import org.apache.jena.query.QueryExecution;
import org.apache.jena.query.QueryExecutionFactory;
import org.apache.jena.query.QueryFactory;
import org.apache.jena.query.QuerySolution;
import org.apache.jena.query.ResultSet;
import org.apache.jena.query.ResultSetFormatter;
import org.apache.jena.rdf.model.Literal;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.RDFNode;
import org.apache.jena.rdf.model.Resource;
import org.apache.jena.rdf.model.Statement;
import org.apache.jena.rdf.model.StmtIterator;
import org.apache.jena.util.FileManager;

public class Main {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        String queryString = "PREFIX owl: <http://www.w3.org/2002/07/owl#>"
                + "PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>"
                + "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>"
                + "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>"
                + "PREFIX foaf: <http://xmlns.com/foaf/0.1/>" + "PREFIX dc: <http://purl.org/dc/elements/1.1/>"
                + "PREFIX dbr: <http://dbpedia.org/resource/>" + "PREFIX dbpedia2: <http://dbpedia.org/property/>"
                + "PREFIX dbpedia: <http://dbpedia.org/>" + "PREFIX skos: <http://www.w3.org/2004/02/skos/core#>"
                + "PREFIX dbo: <http://dbpedia.org/ontology/>" + "select distinct ?p ?o where {"
                + "dbr:Cristiano_Ronaldo ?p ?o " + "filter(langMatches(lang(?o),'en'))" +

        "}";
        Query query = QueryFactory.create(queryString);
        QueryExecution qexec = QueryExecutionFactory.sparqlService("http://dbpedia.org/sparql", query);
        ResultSet results = qexec.execSelect();
        FileOutputStream oFile;
        try {
            oFile = new FileOutputStream("output4.json", false);
            ResultSetFormatter.outputAsJSON(oFile, results);

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        qexec.close();

        FileManager.get().addLocatorClassLoader(Main.class.getClassLoader());
        Model model = FileManager.get().loadModel("output4.json", null, "RDF/JSON");

        StmtIterator iter = model.listStatements();
        try {
            while (iter.hasNext()) {
                Statement stmt = iter.next();
                Resource s = stmt.getSubject();
                Resource p = stmt.getPredicate();
                RDFNode o = stmt.getObject();
                System.out.println(s.toString());
                System.out.println(p.toString());
                System.out.println(o.toString());
            }
        } finally {
            if (iter != null)
                iter.close();
        }

    }

}

As per AKSW suggestion I have tried it with the construct query:

import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import org.apache.jena.query.Query;
import org.apache.jena.query.QueryExecution;
import org.apache.jena.query.QueryExecutionFactory;
import org.apache.jena.query.QueryFactory;
import org.apache.jena.query.ResultSetFactory;
import org.apache.jena.query.ResultSetFormatter;
import org.apache.jena.query.ResultSetRewindable;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.RDFNode;
import org.apache.jena.rdf.model.Resource;
import org.apache.jena.rdf.model.Statement;
import org.apache.jena.rdf.model.StmtIterator;
import org.apache.jena.util.FileManager;

public class Main {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        String queryString = "PREFIX owl: <http://www.w3.org/2002/07/owl#>"
                + "PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>"
                + "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>"
                + "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>"
                + "PREFIX foaf: <http://xmlns.com/foaf/0.1/>" + "PREFIX dc: <http://purl.org/dc/elements/1.1/>"
                + "PREFIX dbr: <http://dbpedia.org/resource/>" + "PREFIX dbpedia2: <http://dbpedia.org/property/>"
                + "PREFIX dbpedia: <http://dbpedia.org/>" + "PREFIX skos: <http://www.w3.org/2004/02/skos/core#>"
                + "PREFIX dbo: <http://dbpedia.org/ontology/>" + "select distinct ?p ?o where {"
                + "dbr:Cristiano_Ronaldo ?p ?o " + "filter(langMatches(lang(?o),'en'))" +

        "}";
        Query query = QueryFactory.create(queryString);
        QueryExecution qexec = QueryExecutionFactory.sparqlService("http://dbpedia.org/sparql", query);


        FileOutputStream oFile;
        try {
            oFile = new FileOutputStream("output4.ttl", false);
            Model result21 = qexec.execConstruct();
            result21.write(oFile, "TURTLE");

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        qexec.close();
        FileManager.get().addLocatorClassLoader(Main.class.getClassLoader());
        Model model = FileManager.get().loadModel("output4.ttl", null, "TURTLE");

        StmtIterator iter = model.listStatements();
        try {
            while (iter.hasNext()) {
                Statement stmt = iter.next();
                Resource s = stmt.getSubject();
                Resource p = stmt.getPredicate();
                RDFNode o = stmt.getObject();
                System.out.println(s.toString());
                System.out.println(p.toString());
                System.out.println(o.toString());
            }
        } finally {
            if (iter != null)
                iter.close();
        }

    }

}

The printed results are weird and doesn't provide the subjects, objects and predicates properly. Below is the response printed in the console: result

The problem is that you're running a SELECT query which gives you back a resultset. This resultset does not represent the RDF triples as you probably expect. Especially since you only select p and o , thus, the subject would be missing. Then you save that resultset as JSON, see https://www.w3.org/TR/rdf-sparql-json-res/ for a description of the format. As a consequence, there are no triples in the JSON file that you can load into a JENA model back.

The solution would be to use SPARQL CONSTRUCT instead. The query could be as follows:

PREFIX dbr: <http://dbpedia.org/resource/> 
CONSTRUCT {
   dbr:Cristiano_Ronaldo ?p ?o .
} WHERE {
   dbr:Cristiano_Ronaldo ?p ?o . 
   FILTER(LANGMATCHES(LANG(?o),'en'))
}

In addition, you have to adapt the method call in the Jena API:

Model model = qexec.execConstruct(); // instead of execSelect();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM