Neil Graham
Neil Graham

Reputation: 893

SPARQL: DELETE if subject contains 1 triple and has predicate

I was wondering if anyone knew of a way to DELETE a triple based on 2 conditions:

The obstacle I'm coming across with these 2 conditions is that in order to COUNT the number of statements on a subject, you must do GROUP BY ?s. Then you do not have the ability to filter any ?p value.

The most likely solution would be a subquery, but I am not sure how this would be structured.

Upvotes: 1

Views: 56

Answers (2)

Joshua Taylor
Joshua Taylor

Reputation: 85923

Does something like this work?

I assume that by "Subject has a triple count of 1" you mean that there is only one triple with this subject. For the case of 1, this is a bit easier since we can just check that "there does not exist another triple for the same subject."

DELETE { ?s ?p ?o }
WHERE {
  ?s ?p ?o 

  #-- the value of ?p is the predicate of interest.
  #-- Alternatively, this could be a FILTER involving
  #-- the variable ?p .
  values ?p { <the-predicate> }

  #-- There is no other triple with ?s as the subject
  #-- that has a different subject or object.  (I.e., 
  #-- the only triple with ?s as a subject is with ?p 
  #-- and ?o .
  filter not exists {
    ?s ?pp ?oo
    filter (?pp != ?p || ?oo != ?o)
  }
}

Upvotes: 0

Ora Lassila
Ora Lassila

Reputation: 402

I would write it like this:

DELETE { ?s ?p ?o }
WHERE {
    {
        SELECT ?s (COUNT(*) AS ?c) {
            ?s ?p ?o
        }
        GROUP BY ?s
    }
    FILTER (?c = 1)
    ?s ?p ?o
}

Upvotes: 1

Related Questions