'Query in Sparql, find first layer of transitive actual nodes

I'm trying to find all actual nodes 'directly'(ignore blank nodes) connect to target node.

eg.

Object1 <predicate1> ObjectX .

Object2 <predicate2> _:BlankNode1 .
_:BlankNode1 <predicate3> ObjectX .

Object3 <predicate4> _:BlankNode2 .
_:BlankNode2 <predicate5> _:BlankNode3 .
_:BlankNode3 <predicate6> ObjectX .

Object4 <predicate7> Object3 .

Is there a way I can find Object1, Object2 and Object3, but not Object4?

Thanks,

Shane.



Solution 1:[1]

You should try this:

SELECT ?object
WHERE {
    ?object (:p|!:p)+ :ObjectX . #The object is connected to the target via any property, with an arbitrary path length greater than 1.
    FILTER NOT EXISTS {
        ?object (:p|!:p)+ ?notBlank . #But there is no path which involves a non-blank node.
        ?notBlank (:p|!:p)+ :ObjectX .
        FILTER(!ISBLANK(?notBlank))
    }
    FILTER(!ISBLANK(?object)) #Finally, the object is not blank
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Valerio Cocchi