1

I have an RDF document which contains:

:booklist :contains ( :Book1 :Book2 :Book3 ) .

And I want to create a SPARQL CONSTRUCT query to create an RDF document which contains:

:Book1 :order 1 .
:Book2 :order 2 .
:Book3 :order 3 .

I know how to loop over the RDF List but don't know how get the iteration on order numbers. E.g. this gives me the list but not the order number.

CONSTRUCT {
   ?book :order 1 
} WHERE {
   ?collection :contains/rdf:rest*/rdf:first ?book .
}
```

1 Answers1

0

A solution has been provided by Labra in this answer Is it possible to get the position of an element in an RDF Collection in SPARQL?

The trick can be summarised as follows. Input data:

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

:booklist :contains ( :Book1 :Book2 :Book3 ) .

SPARQL:

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

CONSTRUCT {
    ?part :order ?position .
} WHERE {
   SELECT ?part (count(?mid) - 1 AS ?position) WHERE {
                ?thing :contains/rdf:rest* ?mid .
                ?mid rdf:rest* ?node .
                ?node rdf:first ?part .
            } GROUP BY ?node ?part
}

which results in:

<http://example.org/#Book1> <http://example.org/#order> 0.
<http://example.org/#Book2> <http://example.org/#order> 1.
<http://example.org/#Book3> <http://example.org/#order> 2.

It is still an open question for me how to go how to go in the opposite direction.