Search code examples
sparqlrdf

Doing DISTINCT on a subject in WHERE clause SPARQL query


My data schema is as: <user> <:bought> <book>

I am trying to write a recommendation query for suggesting new books to a user. For eg. if a user u_a has bought books b_1 and b_2. I find all the users (other than u_a) who bought b_1 and b_2, and those other users bought other books (other than b_1 and b_2).

SELECT ?otherbooks (COUNT(*) AS ?t)
FROM <https://book_store1>
WHERE {
    <https://book_store1/userId/1495865> <https://book_store1/bought> ?booksbought .
    FILTER (?user != <https://book_store1/userId/1495865>)
    ?user <https://book_store1/bought> ?booksbought .
    FILTER (?otherbooks != ?booksbought)
    ?user <https://book_store1/bought> ?otherbooks .
    }
GROUP BY ?otherbooks
ORDER BY DESC (?t)
LIMIT 10

In the 3rd line in WHERE clause i.e. ?user <https://book_store1/bought> ?booksbought ., I want to do DISTINCT users i.e. u_b and u_c might have bought both b_1 and b_2. So, I want to pass single value as u_b and u_c each as ?user in subsequent WHERE clause


Solution

  • Adapt your count to look at unique users, like this:

    SELECT ?otherbooks (COUNT(DISTINCT ?user) AS ?t)