Check multiple resources exist or not via SPARQL query
Asked Answered
N

1

6

I have multiple resources like A, B, C.

I want to know these resources exist in my database or not.

Here is a sample of query for one of them:

ASK { <http://fkg.iust.ac.ir/resource/A> ?p  ?o }

This query returns true or false.

It's better to use one query, and I need to get 2 columns, resource & existing.

Here is my sample response:

---------------------------------------------------
|        resource        |        existing        |
|========================|========================|
|           :A           |          true          |
|------------------------|------------------------|
|           :B           |          false         |
|------------------------|------------------------|
|           :C           |          true          |
---------------------------------------------------

I know ASK and UNION, but how can I put them together for this sample?

Nystrom answered 14/5, 2019 at 20:16 Comment(5)
w.wiki/3yPOutspread
what's the wdt:P361 in your sample? @StanislavKralinNystrom
wdt:P361 is 'part of'.Outspread
Thanks for saving my time, find it with your help. @StanislavKralinNystrom
It's a really good question so I'll post an answer (the same as @StanislavKralin's basically, but not specific to Wikidata) for the benefit of future readers who may find this via Google.Popularity
P
6

Query:

PREFIX : <http://fkg.iust.ac.ir/resource/>

SELECT ?resource (EXISTS { ?resource ?p ?o } AS ?existing) {
    VALUES ?resource { :A :B :C }
}

Test data:

<http://fkg.iust.ac.ir/resource/A> a _:dummy.
<http://fkg.iust.ac.ir/resource/C> a _:dummy.

Result:

-----------------------
| resource | existing |
=======================
| :A       | true     |
| :B       | false    |
| :C       | true     |
-----------------------
  1. To get a tabular result, use SELECT instead of ASK
  2. To get multiple solution for a known list of resources, use VALUES
  3. EXISTS is like a mini-ASK query that can be embedded into expressions
  4. Use the SELECT (expression AS ?variable) form to bind the result of the mini-ASK to the variable ?existing
  5. Caveat: The answer depends on what you mean by “a resource exists”. In an RDF graph, nodes are not created and deleted explicitly, but they exist simply by virtue of being used in a triple. The original ASK query as written checks whether there is any triple that has the node as its subject. For completeness, one may want to check for the object position as well:
    (EXISTS { ?resource ?p ?o } || EXISTS { ?s ?p ?resource })
    
Popularity answered 15/5, 2019 at 7:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.