Search code examples
filtersparqlwikidata

SPARQL - Filter results for which objects explicitly match pattern


For a given SPARQL query I wonder how to explicitly match objects to a pattern i.e. it should have a set of given property values and only those values. Consider the following query: `

SELECT DISTINCT ?person ?personLabel     
WHERE {
#P735 given name , wd:Q4844560 Sebastian ,wd:Q11122389 Johann
  ?person wdt:P735  wd:Q4844560,wd:Q11122389 .  
  SERVICE wikibase:label {bd:serviceParam wikibase:language "en"}
}

` The query matches any subject which has given name Johann and a given name Sebastian, this also matches a subject with more given names e.g. Johann Sebastian Gottfried. I wonder how to filter the query to return those who explicitly have the given names Johann and Sebastian and nothing else.

I have tried using various subqueries and filters but non prevail.


Solution

  • You could use FILTER NOT EXISTS to exclude persons which have any other given name than the two specified ones:

    ?person wdt:P735 wd:Q4844560 , wd:Q11122389 .
    
    FILTER NOT EXISTS { 
      ?person wdt:P735 ?givenName .
      FILTER( ?givenName != wd:Q4844560 && ?givenName != wd:Q11122389 ) .
    }