Cathy Shapiro
Cathy Shapiro

Reputation: 13

Getting labels for multiple uri's in a single sparql query

If we have a set of URI's, how do we get the labels for all of them in a SINGLE SPARQL QUERY?

ie. Given, uri1, uri2, uri3 ... we want the query to give us

uri1 label1

uri2 label2

uri3 label3

While we could issue separate queries for getting the labels for each uri, we would ideally like to avoid making a large number of requests.

I have tried to think in terms of construct, unions and subqueries, with little success.

Thanks!

Upvotes: 1

Views: 2315

Answers (1)

cygri
cygri

Reputation: 9482

You don't say how the labels are expressed in your RDF data, so I assume that they're connected to the URIs with the rdfs:label property. Then the query is simply this:

PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT ?uri ?label { ?uri rdfs:label ?label }

If you want only the labels for only specific URIs, you can get that by filtering on the ?uri variable:

PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT ?uri ?label {
    ?uri rdfs:label ?label
    FILTER (?uri = ex:resource1 || ?uri = ex:resource2 || ?uri = ex:resource3)
}

Or, if your store supports SPARQL 1.1:

PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT ?uri ?label {
    ?uri rdfs:label ?label
    FILTER (?uri IN (ex:resource1, ex:resource2, ex:resource3))
}

Upvotes: 5

Related Questions