Jimo
Jimo

Reputation: 163

How can I get inner join of two graphs in Apache Jena with SPARQL without UNION/FILTER?

I have an Apache Jena based ontology and I have two named graphs in it:

m_p

p1    pred1    mp1
p2    pred1    mp1
p3    pred1    mp2
p4    pred1    mp2
p5    pred1    mp3
p6    pred1    mp3

and m_p_s

mp1   pred2    w:frnd
mp1   pred2    w:fdlfkdl
mp2   pred2    w:kdsjflk
mp2   pred2    w:jflksdlkj
mp3   pred2    w:frnd
mp3   pred2    w:fjksldjfls

and I want to get all the triples in m_p, which objects are predicates in m_p_s and the object of that predicates in m_p_s is w:frnd

In other words I want to make query that returns (results with) p1, p2, p5 and p6 from m_p and doesn’t return p3 and p4.

I’m trying to do this with nested queries, but it doesn’t work: E.g.

SELECT $subj $pred $pr
FROM NAMED named_graph:m_p
WHERE
{
    SELECT $pr
    WHERE
    {
       GRAPH named_graph:m_p_s { $pr $pred0 w:frnd }
    }
}

returns empty result. I tried different things, but either I get an error or empty result or everything in m_p.

I don’t want to use UNION or FILTER for performance reasons.

Do you have an idea how I can do it?

Regards, Stefan

Upvotes: 0

Views: 545

Answers (2)

AndyS
AndyS

Reputation: 16630

The inner SELECT isn't necessary: it hides the second use of ?p but that can be done by using a different name:

SELECT ?s ?p ?o
FROM named_graph:m_p
FROM NAMED named_graph:m_p_s
{
   ?s ?p ?o
   GRAPH named_graph:m_p_s { ?o ?px w:frnd }
}

Upvotes: 2

UninformedUser
UninformedUser

Reputation: 8465

I don't get what you mean by "I want to get all the triples in m_p, which objects are predicates in m_p_s". If you mean "whose objects are subjects in m_p_s", it would make more sense:

SELECT *
FROM named_graph:m_p
FROM NAMED named_graph:m_p_s
WHERE
{
  ?s ?p ?o
  {
     SELECT ?o WHERE {
       GRAPH named_graph:m_p_s { ?o ?p w:frnd }
      }
  }
}

Upvotes: 1

Related Questions