简体   繁体   中英

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?

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 ie 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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM