sparqlknowledge-graph

Filter for triples in default graph (outside all named graphs) with SPARQL


In the below query I extract all entities with class :Entity, regardless of whether they live inside a specific context (named graph) or not.

SELECT ?s
WHERE {
    ?s a :Entity .
}

I would like to filter among these entities, to keep only those that don't live inside any named graph, i.e., only the entities that exist outside all named graphs (EDIT: I guess the correct terminology is that I want to search for triples only in the default graph).

How can I do this?


Solution

  • You can take advantage of the FILTER NOT EXISTS (see here).

    In particular, you are looking for resources (I assume IRIs) that exists in the default graph, but not in any named graphs.

    So a query like this will work:

    SELECT ?s
    WHERE {
     ?s a :Entity
    FILTER NOT EXISTS {
     GRAPH ?g {
      ?s ?p ?o 
      }
     }
    }
    

    This is saying that ?s is not the subject of any triple in any named graph. We can extend the query above to include the case where ?s is not the object of any triple too:

    SELECT ?s
    WHERE {
     ?s a :Entity
    FILTER NOT EXISTS {
     GRAPH ?g {
      {?s ?p ?o}
      UNION
      {?x ?p ?s}
       }
      }
    }