user3493042
user3493042

Reputation: 3

How to retrieve all resources of a given class connected to a given value

Is it possible, with a SPARQL query, to retrieve all resources of a given class C, in the model connected to a given literal?

For example:

S1, p1, o1
S1, type, C
O1, p2, L1

S2, p3, o2
S2, type, C
O2, p4, o3
O3, p5, L1

For literal L1, I want to retrieve S1 and S2.

Upvotes: 0

Views: 67

Answers (1)

Joshua Taylor
Joshua Taylor

Reputation: 85873

It's always easier if you provide data that we can actually use. For instance, here's your data in Turtle, and in a way that we can actually query. In the future, please try to provide a minimal sample of data that we can use.

@prefix : <urn:ex:>

:s1 a :C ;
    :p1 :o1 .

:o1 :p2 "l1" .

:s2 a :C ;
    :p3 :o2 .

:o2 :p4 :o3 .

:o3 :p5 "l1" .

Here's a query that finds a path from a subject ?s that is an instance of :C to the literal "l1". The (:|!:)* is a property path using a "wildcard". Since we've defined the : prefix, : is an IRI, and since every IRI is either : or not (!:), a path of zero or more repetitions of :|!: is an path from ?s to "l1". See SPARQL property path queries with arbitrary properties for more about wildcard property paths.

prefix : <urn:ex:>

select ?s {
  ?s a :C ; (:|!:)* "l1"
}
-------
| s   |
=======
| :s2 |
| :s1 |
-------

Upvotes: 2

Related Questions