Generate Graph with sub-Graphs using sparql

偶尔善良 提交于 2019-12-22 10:37:40

问题


I have the following situation in my RDF-store:

Named Graph: A

  S1 P1 O1

Named Graph: B

  S2 P2 O1

Named Graph: C

  S3 P3 O1

I now want to define a SPARQL Query which finds all Graphs where O1 is in the tripples, and stores those 3 Graphs + the tripples in a new Graph with the name A+B+C

NEW Named Graph: A+B+C

Named Graph: A
   S1 P1 O1
Named Graph: B
   S2 P2 O1
Named Graph: C
   S3 P3 O1

With Construct or insert Into i only found out how to build a graph out of tripples, bzw not how to build a graph which contains graphs?

Is this possible, if yes how?

Tank you


回答1:


You can't do exactly what you want because sub-graphs can't be explicitly stored within each other in the way you seem to be describing. However you can put all the triples into a single graph which may prove sufficient:

PREFIX : <http://example.org/>
INSERT
{
  # Output triples in the desired graph
  GRAPH ?name { ?s ?p ?o }
}
WHERE
{
  # Use a sub-query to find all relevant graphs and concatenate their names together
  {
    SELECT (GROUP_CONCAT(STR(?g)) AS ?strName) (URI(?strName) AS ?name)
    WHERE
    {
       GRAPH ?g { ?s ?p :o1 }
    }
    GROUP BY ?g
  }
  # Join the name to all the relevant triples
  GRAPH ?g 
  {
    ?s ?p :o1 .
    ?s ?p ?o .
  }
}

So this is a little hacky but should do roughly what you want. It uses a sub-query to find all the graphs that have the relevant triples and concatenates their name together and turns it into a URI. Note that this may well create a very invalid URI which may mean that the later steps of the query will not work.

It then joins that graph name together with all the triples from the graphs which contain triples with the desired subject.

Finally it outputs these into the graph with the newly created name, depending on the store this is the bit that might not work as you are liable to have created an illegal graph name.

This may not do exactly what you want but hopefully will point you in the right direction.



来源:https://stackoverflow.com/questions/28383932/generate-graph-with-sub-graphs-using-sparql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!