Search code examples
sparqlwikidata

Find which direct property applied in a SPARQL query


I have a list of properties I want to apply to a specific entity mathematics: wd:Q395. In this case:

instanceOf: 'wdt:P31'
subclassOf: 'wdt:P279'

The results are:

Mathematics is instance of academic discipline and Mathematics is subclass of exact science and formal science

Instead of making two different queries I would like to make them all at once:

SELECT ?field ?fieldLabel ?propertyApplied
WHERE {
      wd:Q395 wdt:P31 | wdt:P279  ?field. 
      SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
      BIND("" AS ?propertyApplied)
}

How can I know which property applied to fill the right column? ( for example next to academic discipline I would like that it appears instance of) enter image description here

I tried this but it looks weird and the results repeat themselves.

SELECT ?instanceOf ?subclassOf ?instanceOfLabel ?subclassOfLabel
WHERE {
      OPTIONAL { wd:Q395 wdt:P31 ?instanceOf. }
      OPTIONAL { wd:Q395 wdt:P279 ?subclassOf. }
      SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
}

enter image description here


Solution

  • Use VALUES or UNION:

    SELECT ?field ?fieldLabel ?propertyLabel WHERE {
          VALUES (?predicate) {(wdt:P31) (wdt:P279)}
          wd:Q395 ?predicate ?field . 
          ?property wikibase:directClaim ?predicate .
          SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
    }
    

    Try it!

    SELECT ?field ?fieldLabel ?propertyLabel {
         { wd:Q395 wdt:P31 ?field . BIND (wd:P31 AS ?property) }
          UNION
         { wd:Q395 wdt:P279 ?field . BIND (wd:P279 AS ?property) }
          SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
    }
    

    Try it!