posfan12
posfan12

Reputation: 2651

Filter out string from result set

I have this SPARQL script meant to work on Wikidata:

SELECT
  ?game
  (group_concat(distinct      ?gameLabel ; separator = ", ") AS      ?gameLabels)
  (group_concat(distinct     ?genreLabel ; separator = ", ") AS     ?genreLabels)
  WHERE {
    ?game wdt:P31 wd:Q7889;
    wdt:P136 wd:Q744038.
    OPTIONAL {?game wdt:P136     ?genre}
    SERVICE wikibase:label {
      bd:serviceParam wikibase:language "en".
           ?game rdfs:label      ?gameLabel.
          ?genre rdfs:label     ?genreLabel.
    }
} GROUP BY $game
ORDER BY ASC (?gameLabel)

You can test the code here:

https://query.wikidata.org/

Currently, I am filtering for a genre named "role-playing video game". However, I do not want this string to appear in the result set. How do I filter out just this string but not the actual records? Thanks.

Upvotes: 0

Views: 70

Answers (1)

UninformedUser
UninformedUser

Reputation: 8465

SPARQL is pretty simple, just add the FILTER to the OPTIONAL clause:

SELECT
  ?game
  (group_concat(distinct      ?gameLabel ; separator = ", ") AS      ?gameLabels)
  (group_concat(distinct     ?genreLabel ; separator = ", ") AS     ?genreLabels)
  WHERE {
    ?game wdt:P31  wd:Q7889 ;
          wdt:P136 wd:Q744038.
    OPTIONAL {?game wdt:P136 ?genre . FILTER(?genre != wd:Q744038)}
    SERVICE wikibase:label {
      bd:serviceParam wikibase:language "en".
           ?game rdfs:label      ?gameLabel.
          ?genre rdfs:label     ?genreLabel.
    }
} GROUP BY ?game
ORDER BY ASC (?gameLabel)

Note, this doesn't filter out the genre "action role-playing game". If you also want to omit this one (since it looks like a sub-genre) you have to add this as a second condition to the FILTER:

FILTER(?genre != wd:Q744038 && ?genre != wd:Q1422746)

or if you more resource, it's more compact to

FILTER(?genre NOT IN (wd:Q744038, wd:Q1422746))

Upvotes: 1

Related Questions