sparql

SPARQL values retrieving only 1 sample


I've got several instances of entities of several types in my kg. I'd like to use VALUES to describe all my types and use those values to select 1 (sample) instance and then select all values of that subject. Something like

select * where {

  select ?s where {   
    ?typ VALUES ( ex:t1 ex:t2 ex:t3 ) .
    ?s a ?typ .
    # get one ?s of type ex:t1, ex:t2, ex:t3
  } limit 1
  ?s ?p ?o .
}

above will only grab 1 value before exiting. I've tried putting VALUES outside the subquery and it doesn't work either. Anyway to do what I want?


Solution

  • You need to fix the syntax of VALUES and then actually ask for samples.

    SELECT ?typ (SAMPLE (?s) AS ?sample_s)
    WHERE {
      VALUES ?typ {ex:t1 ex:t2 ex:t3}
      ?s a ?typ .
    }
    GROUP BY ?typ
    LIMIT 3
    

    I added GROUP BY for clarity. You can omit it.

    If you want a single result with three samples, you get that using subqueries.

    SELECT ?s1 ?s2 ?s3
    WHERE {
      {
        SELECT ?s1 WHERE {
          ?s1 a ex:t1 .
        } LIMIT 1
      }
      {
        SELECT ?s2 WHERE {
          ?s2 a ex:t2 .
        } LIMIT 1
      }
      {
        SELECT ?s3 WHERE {
          ?s3 a ex:t3 .
        } LIMIT 1
      }
    }
    LIMIT 1
    

    Update based on your comment

    Hi, I indeed want your second example but have 30 values to use

    Not much more can be done with SPARQL 1.1 but asking for samples separately is perhaps shorter than 30 subqueries:

    SELECT 
      (SAMPLE(?st1) AS ?t1_sample)
      (SAMPLE(?st2) AS ?t2_sample)
      (SAMPLE(?st3) AS ?t3_sample)
    WHERE {
      { ?st1 a ex:t1 }
      { ?st2 a ex:t2 }
      { ?st3 a ex:t3 }
    }
    LIMIT 1