Search code examples
sparql

Find orphan nodes with SPARQL


I am trying to find orphan nodes (nodes which do not have any incoming relations) with SPARQL in a Fuseki database. I tried several queries which all do not return correct results.

I tried the following:

Query 1 (got this from linkedIn)

  select ?o ?isOrphan where {  GRAPH <http://localhost:8080/catalog/-1305288727> {
      ?s ?p ?o .
      FILTER(!isLiteral(?o))
    bind(!(EXISTS {?o ?p1 ?o2}) as ?isOrphan)}}

Query 2

SELECT ?source ?s ?p ?o
WHERE { GRAPH <http://localhost:8080/catalog/-1305288727>{
    ?s ?p ?o  .
    FILTER EXISTS {?source ?p ?s  } .
 }
}

Query 3 - unbound variable pp in FILTER

  SELECT ?source ?s ?p ?o
WHERE { GRAPH <http://localhost:8080/catalog/-1305288727>{
    ?s ?p ?o  .
    FILTER EXISTS {?source ?pp ?s  } .
 }
}

Any help is highly appreciated.


Solution

  • This query finds each entity that is the subject of any triple, and then checks that this entity is not the object of any triple.

    SELECT ?orphan
    FROM <http://localhost:8080/catalog/-1305288727>
    WHERE {
    
      ?orphan ?p1 [] .
    
      FILTER NOT EXISTS { ?linkingNode ?p2 ?orphan . }
    
    }