How to use the ASK WHERE statement with multiple conditions (sparql)

963 views Asked by At

I want to check if an entity has one of the types listed below. If it does then the query must return true.

PREFIX basekb:<http://rdf.basekb.com/ns/>

basekb:music.release_track
basekb:book.written_work
basekb:book.book
basekb:music.release
basekb:music.album
basekb:tv.tv_series.episode
basekb:music.composition
basekb:music.recording
basekb:film.film
basekb:fictional_universe.fictional_character

Entity m.0109yb6 has the following types. The sparql query should return true

http://rdf.basekb.com/ns/common.topic
http://rdf.basekb.com/ns/music.recording

Question

I came out with following query. Is there a better approach to solve this problem?

PREFIX basekb:<http://rdf.basekb.com/ns/>
PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX rdf1:<http://www.w3.org/2000/01/rdf-schema#>

ASK where 
{
          {basekb:m.0109yb6 rdf:type ?x; rdf:type basekb:music.release_track} 
    UNION {basekb:m.0109yb6 rdf:type ?x; rdf:type basekb:book.written_work}
    UNION {basekb:m.0109yb6 rdf:type ?x; rdf:type basekb:book.book}
    UNION {basekb:m.0109yb6 rdf:type ?x; rdf:type basekb:music.release}
    UNION {basekb:m.0109yb6 rdf:type ?x; rdf:type basekb:music.album}
    UNION {basekb:m.0109yb6 rdf:type ?x; rdf:type basekb:tv.tv_series.episode}
    UNION {basekb:m.0109yb6 rdf:type ?x; rdf:type basekb:music.composition}
    UNION {basekb:m.0109yb6 rdf:type ?x; rdf:type basekb:music.recording}
    UNION {basekb:m.0109yb6 rdf:type ?x; rdf:type basekb:film.film}
    UNION {basekb:m.0109yb6 rdf:type ?x; rdf:type basekb:fictional_universe.fictional_character}
}

Answer: TRUE

1

There are 1 answers

2
Joshua Taylor On BEST ANSWER

The query as you've written it is kind of odd. There's no use of the ?x variable, so you can immediately simplify it as:

ASK where 
{
          {basekb:m.0109yb6 rdf:type basekb:music.release_track} 
    UNION {basekb:m.0109yb6 rdf:type basekb:book.written_work}
    #-- ...
    UNION {basekb:m.0109yb6 rdf:type basekb:fictional_universe.fictional_character}
}

That's still got lots of repeated code, though. You can use SPARQL 1.1's values to specify the permissible values of a variable ?type, and then just ask whether your entity has one of those values for rdf:type:

prefix basekb:<http://rdf.basekb.com/ns/>
prefix rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#>

ask where {
  basekb:m.0109yb6 rdf:type ?type
  values ?type {
    basekb:music.release_track
    basekb:book.written_work
    basekb:book.book
    basekb:music.release
    basekb:music.album
    basekb:tv.tv_series.episode
    basekb:music.composition
    basekb:music.recording
    basekb:film.film
    basekb:fictional_universe.fictional_character
  }
}