Search code examples
jenaapache-jena

Fail to load turtle files using jena assembler file


I define an assembler file with name dataset2.ttl. The content of this file is:

@prefix tdb:     <http://jena.hpl.hp.com/2008/tdb#> .

@prefix rdf:     <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .

@prefix rdfs:    <http://www.w3.org/2000/01/rdf-schema#> .

@prefix ja:      <http://jena.hpl.hp.com/2005/11/Assembler#> .

[] ja:loadClass "com.hp.hpl.jena.tdb.TDB" .
tdb:DatasetTDB  rdfs:subClassOf  ja:RDFDataset .
tdb:GraphTDB    rdfs:subClassOf  ja:Model .
<#dataset> rdf:type         tdb:DatasetTDB ;
   tdb:location "DB" ;
   tdb:unionDefaultGraph true ;
   .

<#data1> rdf:type tdb:GraphTDB ;
    tdb:dataset <#dataset> ;
    tdb:graphName <http://example.org/data1> ;
    ja:content [ja:externalContent <file:///C:/Users/data/data1.ttl>;];
    .

The related jena code to create a datase is:

public class TDB {

public static void main(String[] args) {
    Dataset ds = null;
    try {
        ds = TDBFactory.assembleDataset("Dataset2.ttl");

        if(ds == null) {

            System.out.println("initial tdb failed");
        } else {
            System.out.println("Default Model:");

            Model model = ds.getDefaultModel();

            ds.begin(ReadWrite.WRITE);
            model.write(System.out, "TURTLE");
        }
    } finally {
        if(ds != null) {
            ds.close();
        }
    }
}

The content in data1.ttl is:

@prefix : <http://example.org/> .
@prefix foaf:   <http://xmlns.com/foaf/0.1/> .

:alice
a           foaf:Person ;
foaf:name   "Alice" ;
foaf:mbox   <mailto:alice@example.org> ;
foaf:knows  :bob ;
foaf:knows  :charlie ;
foaf:knows  :snoopy ;
.

:bob
foaf:name   "Bob" ;
foaf:knows  :charlie ;
.

:charlie
foaf:name   "Charlie" ;
foaf:knows  :alice ;
.

A dataset has been created using this code. However, the content in the file of "data1.ttl" has not been read into the model. What is the problem of my code?


Solution

  • You also have

    <#dataset> rdf:type         tdb:DatasetTDB ;
       tdb:location "DB" ;
       tdb:unionDefaultGraph true ;
       .
    

    and

    ds = TDBFactory.assembleDataset("Dataset2.ttl");
    

    so you are asking Jena to assemble a dataset. That dataset will be <#dataset> (find by the type). It is not connected the graph you define so that's ignored; you can remove that part. Assembling the dataset is the way to do this.

    You have tdb:unionDefaultGraph true so the default graph for query is the combination of all named graphs in the dataset.

    Pick one out with model.getNamedModel.

    If you use SPARQL, use the GRAPH keyword.