Ania David
Ania David

Reputation: 1198

sparql how to sub query into another query

I have this data

@prefix : <http://test.example/> .

:alice :likes :beethoven.
:alice :likes :verdi.
:sofia :likes :beethoven.
:sofia :likes :verdi.
:sofia :likes :rossini.
:ania :likes :verdi.
:ania :likes :beethoven.
:ania :likes :david.
:david :likes :ania.
:david :likes :beethoven.
:david :likes :verdi.
:antonino :likes :verdi.
:antonino :likes :mozart.
:weirdo :likes :katyperry.
:beethoven a :recommendable.
:verdi a :recommendable.
:rossini a :recommendable.
:katyperry a :recommendable.
:mozart a :recommendable.

and I make a query to get the users that likes the same items as a specific user

select ?anotherUser (COUNT(?anotherItem) as ?countOfItems) WHERE {
  values ?user {:ania}
  ?anotherUser :likes ?anotherItem.
  filter (?anotherUser != ?user)
  filter exists {?user :likes ?anotherItem}
}group by ?anotherUser
order by desc(?countOfItems)

now I want to get the items that these users like (but of course without the items that they share with that specific user (:ania))

I know I have to include a query inside the other, I tried a lot myself but no success, could you help please?

Upvotes: 1

Views: 2806

Answers (1)

chris
chris

Reputation: 1817

now I want to get the items that these users like (but of course without the items that they share with that specific user (:ania))

I know I have to include a query inside the other, I tried a lot myself but no success, could you help please?

I believe the main thing to keep in mind is that subqueries are evaluated foremost i.e. the query is evaluated from the innermost first, to the outermost.

So the following query:

prefix : <http://test.example>
select distinct ?user ?anotherUser ?item WHERE {
  ?anotherUser :likes ?item.
  filter not exists {?user :likes ?item}
  {select ?user ?anotherUser where {
    values ?user {:ania}
    ?anotherUser :likes ?anotherItem.
    filter (?anotherUser != ?user)
    filter exists {?user :likes ?anotherItem}
  }}
}

will produce the result:

----------------------------------
| user  | anotherUser | item     |
==================================
| :ania | :sofia      | :rossini |
| :ania | :antonino   | :mozart  |
| :ania | :david      | :ania    |
----------------------------------

which is what you asked for right?

Upvotes: 5

Related Questions