Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join SPARQL Query

Tags:

sparql

I have multiple graphs in RDF Knowledgebase

for example
<123> <hasValue> "23" <graph1>
<234> <hasValue> "47" <graph1>
<374> <hasValue> "23" <graph1>
-----------
----------
<456> <hasFeature> "50" <graph2>
<244> <hasFeature> "23" <graph2>
<123> <hasFeature> "23" <graph2>
---------------------

Now I wan to run SPARQL query to get the results which is common in both graphs.

suppose If I run the following query for one graph I get the following result

SELECT ?subject 
FROM Named <http://www.xyz.com/namespace/graph1>
WHERE {GRAPH ?graph
   {?subject prefix:hasValue "23" .}} 

<123>
<374>
---
---
---

if run the following second query for graph2 I get the following

SELECT ?subject 
FROM Named <http://www.xyz.com/namespace/graph2>
WHERE {GRAPH ?graph
   {?subject prefix:hasFeature "23" .}} 

<244>
<123>
-----

However I want the subject <123> which is common in both queries. Is any way we can combine both queries to get the only subject which is common in both queries. Thanks in advance.

like image 742
user3061324 Avatar asked Sep 19 '26 22:09

user3061324


1 Answers

Yes, joining in SPARQL is simply a case of stating multiple patterns that have common variables. So we can mostly just cut and past the your two queries together:

SELECT ?subject 
FROM NAMED <http://www.xyz.com/namespace/graph1>
FROM NAMED <http://www.xyz.com/namespace/graph2>
WHERE 
{
  GRAPH <http://www.xyz.com/namespace/graph1> 
  {
    ?subject prefix:hasValue "23" .
  }
  GRAPH <http://www.xyz.com/namespace/graph2> 
  {
    ?subject prefix:hasFeature "23" .
  }
} 

Note that since you're now querying the two graphs separately we need to explicitly name the graph for each of the GRAPH clauses. We can't just use a single GRAPH ?graph pattern because that matches each named graph individually and unions the results together which does not have the semantics you desire.

With this query the results for the two graphs will now be joined together so you'll only get results where the pattern matches in both graphs.

like image 115
RobV Avatar answered Sep 22 '26 14:09

RobV



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!