Yunfeng Wang
Yunfeng Wang

Reputation: 41

SPARQL Query with quantifier

I need to query using quantifier such as ANY(∀). For example:

Data

:a :to :b . (b is a non_target_type)
:b :to :c . (c is a target_type)
:c :to :d . (d is a non_target_type)
:d :to :e . (e is a target_type)
:e :to :f . (f is a target_type)

A query is like

:a -> ?y -> ?z .
?z a :target_type .
∀?y, ?y is not a :target_type . (Here's the problem)

Then I expect to get ?z only contains :c How can I get the result by sparql?

Upvotes: 1

Views: 124

Answers (2)

Yunfeng Wang
Yunfeng Wang

Reputation: 41

Here is the graph and query result. What I expect is result ":d", other than ":d and :g".

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

ns:a ns:to ns:b .
ns:b ns:to ns:c .
ns:c ns:to ns:d .
ns:d ns:to ns:e .
ns:e ns:to ns:f .
ns:f ns:to ns:g .
ns:g ns:to ns:h .

ns:a rdf:type ns:target .
ns:d rdf:type ns:target .
ns:g rdf:type ns:target .

enter image description here

Upvotes: 0

Joshua Taylor
Joshua Taylor

Reputation: 85883

It sounds like you're asking for

SELECT ?z WHERE {
  :a :to ?y .
  ?y :to ?z .
  ?z a :targetType .
  FILTER NOT EXISTS {
    ?y a :targetType
  }
}

This finds any ?z such that:

  • ?z a :target_type; and
  • :a is connected to something that is connected to ?z; and
  • it's not the case that ?y a :targetType

That would be mean that :a is connected through some ?y to :z such that ?y isn't a :targetType. But if you want to make sure that there's no such ?y that is a :targetType, you'd use:

SELECT ?z WHERE {
  :a :to/:to ?z .
  ?z a :targetType .
  FILTER NOT EXISTS {
    :a :to ?y .
    ?y :to ?z .
    ?y a :targetType
  }
}

Upvotes: 1

Related Questions