I want to extract a chain of instances between two instances of my ontology by asking a SPARQL query. for example in the following figure if I want to know how A is connected to E, the result of query should be something like a list of A, B, D, F, E.
how the ontology should be designed and query should be built? Is it even possible?
This isn't too hard. In RDF, your data can be something as simple as a direct encoding of the graph:
@prefix : <urn:ex:>
:A :connectedTo :B .
:B :connectedTo :C, :D .
:D :connectedTo :F .
:F :connectedTo :E, :G .
Then, using SPARQL property paths, you can find every node such that there's a path of connectedTo properties from A to it and from it to E, including A and E themselves:
prefix : <urn:ex:>
select ?mid where {
:A :connectedTo* ?mid .
?mid :connectedTo* :E .
}
-------
| mid |
=======
| :D |
| :F |
| :B |
| :A |
| :E |
-------
If you want to get those in order, you can additionally count how many things are between A and the "mid-node". (This is described in my answer to Is it possible to get the position of an element in an RDF Collection in SPARQL?)
prefix : <urn:ex:>
select ?mid (count(?premid) as ?i) where {
:A :connectedTo* ?premid .
?premid :connectedTo* ?mid .
?mid :connectedTo* :E .
}
group by ?mid
-----------
| mid | i |
===========
| :D | 3 |
| :F | 4 |
| :E | 5 |
| :B | 2 |
| :A | 1 |
-----------
If you actually want a single result that looks more or less like "A, B, C, D, E, F", then you adapt these queries using the techniques from my answer to Aggregating results from SPARQL query, which shows how to concatenate these into a single string.