sparqljenafusekinamed-graphs

Sparql query to read from all named graphs without knowing the names


I am looking to run a SPARQL query over any dataset. We dont know the names of the named graphs in the datasets.

These are lots of documentation and examples of selection from named graphs when you know the name of the named graph/s. There are examples showing listing named graphs.

We are running the Jena from Java so it would be possible to run 2 queries, the first gets the named graphs and we inject these into the 2nd.

But surely you can write a single query that reads from all named graphs when you dont know their names?

Note: we are looking to stay away from using default graph/s as their behaviour seems implementation dependent.


Solution

  • Example:

    { 
      ?s foaf:name ?name ;
         vCard:nickname ?nickName .
    }
    

    If you want the pattern to match within one graph and wish to try each graph, use the GRAPH ?g form.

    GRAPH ?g
       { ?s foaf:name ?name ;
            vc:nickname ?nickName .
       }
    

    If you want to make a query where the pattern matches across named graphs, -- e.g. foaf:name in one graph and vCard:nickname in another, same subject -- then set union default graph tdb2:unionDefaultGraph true then the default graph as seen by the query is the union (actually, RDF merge - no duplicates) of all the named graphs. Use the pattern as originally given.

    Fuseki configuration file extract:

    :dataset_tdb2 rdf:type  tdb2:DatasetTDB2 ;
        tdb2:location "DB2" ;
        ## Optional - with union default for query and update WHERE matching.
        tdb2:unionDefaultGraph true ;
        .
    

    In code, not Fuseki, the application can use Dataset.getUnionModel().