Alberto
Alberto

Reputation: 3

Get properties from a group of items in with SPARQL

I need to use the SPARQL query service from Wikidata.

What I need to retrieve is a list of all properties that items which are instance of (P31) disease (Q12136) have

I'm having some trouble understanding how to nest two queries

With this Query we have all the items which are instance of disease:

SELECT ?item WHERE { ?item wdt:P31 wd:Q12136 . }

Then this is the list of properties, but instead of searching in the entire site I have to search in the subgroup obtained in the previous sentence

SELECT DISTINCT ?property ?propertyLabel WHERE { ?property a wikibase:Property . SERVICE wikibase:label { bd:serviceParam wikibase:language "en" } } ORDER BY ?propertyLabel

What is the correct way to nest both queries? Also, can you retrieve the type of the properties, too?

Thanks.

Upvotes: 0

Views: 1165

Answers (1)

maxlath
maxlath

Reputation: 1841

The merging of those two queries could look something like:

SELECT DISTINCT ?property ?propertyLabel WHERE {
  ?item wdt:P31 wd:Q12136 .
  ?item ?property ?value .
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en" }
}

[try it]

Notice the DISTINCT keyword, used to de-duplicate properties.

But to get proper property labels (instead of property URIs like http://www.wikidata.org/prop/P279), you need to use a slightly more complex query

SELECT DISTINCT ?property ?propLabel WHERE {
  ?item wdt:P31 wd:Q12136 .
  ?item ?property ?value .
  hint:Query hint:optimizer "None" .
  ?prop wikibase:directClaim ?property .
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en" }
}

[try it]

Then, to also get the property datatype, you can use wikibase:propertyType:

SELECT DISTINCT ?property ?propLabel ?type WHERE {
  ?item wdt:P31 wd:Q12136 .
  ?item ?property ?value .
  # get the property label
  # see https://www.wikidata.org/wiki/Wikidata:SPARQL_query_service/queries#Adding_labels_for_properties
  hint:Query hint:optimizer "None" .
  ?prop wikibase:directClaim ?property .
  ?prop wikibase:propertyType ?type .
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en" }
}

[try it]

Upvotes: 2

Related Questions