Question

For example I have this query

SELECT ?x
WHERE {?x :has_input "z"}

then i want to use the result/s of ?x as object to another query

SELECT ?y
WHERE {?y :uses "x"}

Any ideas how to achieve that? Thanks in advance

Was it helpful?

Solution

For the sake of the example, let's define some data:

@prefix : <http://example.org/> .

:node0 :has_input "w", "z" .
:node1 :has_input "x", "y" .
:node2 :has_input "y", "z" .
:node3 :uses :node2 .
:node4 :uses :node1 .

Based on this data, and with specifying any particular API (because you didn't), you've got a few SPARQL level options. The first is simply combining the queries, which is easy enough in this case:

prefix : <http://example.org/>

select ?y where { 
  ?x :has_input "z" .
  ?y :uses ?x .
}

$ arq --data data.n3 --query combined-query.sparql 
----------
| y      |
==========
| :node3 |
----------

Another option is to use a subquery

prefix : <http://example.org/>

select ?y where { 
  {
    select ?x where { 
      ?x :has_input "z" .
    }
  }
  ?y :uses ?x .
}


$ arq --data data.n3 --query subquery.sparql
----------
| y      |
==========
| :node3 |
----------

A third, which may be what you actually need, if you have to execute the queries separately, is to execute a query that finds values for ?x for you, and then execute a query that finds ?y, but with the ?x values embedded with values. The first query looks like and returns:

prefix : <http://example.org/>

select ?x where { 
  ?x :has_input "z" .
}

$ arq --data data.n3 --query xquery.sparql
----------
| x      |
==========
| :node2 |
| :node0 |
----------

Then, based on those values, you create the query for ?y:

prefix : <http://example.org/>

select ?y where { 
  values ?x { :node2 :node0 }
  ?y :uses ?x .
}

$ arq --data data.n3 --query yquery.sparql
----------
| y      |
==========
| :node3 |
----------
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top