User:Olea/Ejemplos de consultas WDQS
Hello SPARQL queries dataset
[edit]Search for thousands example Wikidata queries: https://observablehq.com/@pac02/hello-sparql-queries-dataset
Uso de UNION
[edit]Profesiones y ocupaciones con entrada eswiki:
- Try it!
SELECT DISTINCT ?profesi_n ?profesi_nLabel ?article WHERE { { ?profesi_n wdt:P31 wd:Q28640. ?article schema:about ?profesi_n . ?article schema:isPartOf <https://es.wikipedia.org/>. } UNION { ?profesi_n wdt:P31 wd:Q12737077. ?article schema:about ?profesi_n . ?article schema:isPartOf <https://es.wikipedia.org/>. } UNION { ?profesi_n wdt:P279 wd:Q28640. ?article schema:about ?profesi_n; schema:isPartOf <https://es.wikipedia.org/>. } UNION { ?profesi_n wdt:P279 wd:Q12737077. ?article schema:about ?profesi_n; schema:isPartOf <https://es.wikipedia.org/>. } SERVICE wikibase:label { bd:serviceParam wikibase:language "es". } } ORDER BY ?profesi_nLabel
Listar elementos con una referencia determinada
[edit]- Try it!
SELECT ?item ?itemLabel WHERE { ?item p:P31 [ps:P31 wd:Q4989906; prov:wasDerivedFrom/pr:P248 wd:Q5917182]. SERVICE wikibase:label { bd:serviceParam wikibase:language "es".} }
Listar calificadores
[edit]- Try it!
SELECT ?eremitorio ?eremitorioLabel ?id ?codigo ?fecha_ini ?fecha_fin ?epoca WHERE { ?eremitorio wdt:P3318 ?id; wdt:P8425 ?codigo; p:P31 ?statement. ?statement a wikibase:BestRank; ps:P31 wd:Q513550. OPTIONAL { ?statement pq:P580 ?fecha_ini. } OPTIONAL { ?statement pq:P582 ?fecha_fin. } OPTIONAL { ?statement pq:P1264 ?epoca. } SERVICE wikibase:label { bd:serviceParam wikibase:language "es".} }
Consulta a partir de una lista de elementos previos conocidos
[edit]- Try it!
SELECT ?municipio ?municipioLabel ?item ?itemLabel ?itemDescription ?coordenadas ?codigoIAPH WHERE { VALUES ?thing { wd:Q1447785 wd:Q1358190 wd:Q1157982 wd:Q1447755 wd:Q1358351 wd:Q695536 wd:Q940842 wd:Q596058 wd:Q1611746 wd:Q1358027 wd:Q1447770 wd:Q1358171 wd:Q1110408 wd:Q1358100 wd:Q1157977 wd:Q1628481 wd:Q1445226 wd:Q1358237 wd:Q1611880 wd:Q1407152 wd:Q1444119 } SERVICE wikibase:label { bd:serviceParam wikibase:language "es". } ?item wdt:P131 ?thing, ?municipio. ?item wdt:P8425 ?codigoIAPH. FILTER NOT EXISTS { ?item wdt:P625 ?coordenadas. } }
Listar un rango de elementos de una consulta usando OFFSET
[edit]- Try it!
SELECT DISTINCT ?item ?cod_IAPH WHERE { ?item (wdt:P131*) wd:Q82142; wdt:P8425 ?cod_IAPH. ?item wdt:P1435 wd:Q23712. } ORDER BY ?cod_IAPH OFFSET 500 LIMIT 500
List an P31 value with a specific reference
[edit]- Try it!
SELECT ?item ?itemLabel WHERE { ?item p:P31 [ps:P31 wd:Q4989906; prov:wasDerivedFrom/pr:P248 wd:Q5917182]. SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". } }
Elementos que usan una propiedad que es instancia de una «propiedad de Wikidata»
[edit]- Try it!
SELECT (COUNT(DISTINCT ?protected_area ) AS ?count) WHERE { { ?prop wdt:P31 wd:Q55978235. ?prop wikibase:directClaim ?claim. ?protected_area ?claim []. } UNION { ?protected_area wdt:P31/wdt:P279* wd:Q473972. } }
Ejemplo de capa en Wikishootme
[edit]?q wdt:P131* wd:Q803684;
wdt:P3318 ?IAPHid
Buscar una cadena de texto en la etiqueta de un elemento
[edit]La palabra mancomunidad en la etiqueta ES de elementos situados en España:
- Try it!
SELECT ?item ?l ?lang { hint:Query hint:optimizer "None". SERVICE wikibase:mwapi { bd:serviceParam wikibase:endpoint "www.wikidata.org" . bd:serviceParam wikibase:api "Generator" . bd:serviceParam mwapi:generator "search" . bd:serviceParam mwapi:gsrsearch 'inlabel:Mancomunidad haswbstatement:P17=Q29' . bd:serviceParam mwapi:gsrlimit "max" . bd:serviceParam mwapi:gsrnamespace "0" . ?item wikibase:apiOutputItem mwapi:title . } ?item rdfs:label ?l. bind(lang(?l) as ?lang) }
La palabra mancomunidad en todas las etiquetas de elementos situados en España:
- Try it!
SELECT ?item ?l ?lang { hint:Query hint:optimizer "None". SERVICE wikibase:mwapi { bd:serviceParam wikibase:endpoint "www.wikidata.org" . bd:serviceParam wikibase:api "Generator" . bd:serviceParam mwapi:generator "search" . bd:serviceParam mwapi:gsrsearch 'inlabel:Mancomunidad haswbstatement:P17=Q29' . bd:serviceParam mwapi:gsrlimit "max" . bd:serviceParam mwapi:gsrnamespace "0" . ?item wikibase:apiOutputItem mwapi:title . } ?item rdfs:label ?l. bind(lang(?l) as ?lang) FILTER(contains(?l, "Mancomunidad")). }
Buscar una cadena de texto en la descripción de un elemento
[edit]# todos los elementos sin instanciar de caracterización arqueológica
# y que, por tanto, son probablemente yacimientos arqueológicos
SELECT DISTINCT ?item ?itemLabel ?itemDescription ?codigo ?identificador WHERE {
?item wdt:P3318 ?identificador.
FILTER(NOT EXISTS { ?item wdt:P31 _:b1. })
?item wdt:P8425 ?codigo;
schema:description ?description.
FILTER(CONTAINS(STR(?description), "arqueológica"))
SERVICE wikibase:label { bd:serviceParam wikibase:language "es". }
}
ORDER BY (?codigo)
Listar enlaces (sitelink) a ESWiki
[edit]- Try it!
SELECT ?article ?articleLabel ?sitelink WHERE { SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],es". } ?article wdt:P131 wd:Q10400. ?sitelink schema:about ?article; schema:isPartOf <https://es.wikipedia.org/>. }
Extraer la URI a una sentencia/afirmación/statement
[edit]- Try it!
SELECT DISTINCT ?item ?itemLabel ?statement1 ?davalue WHERE { ?item p:P4797 ?statement1. ?statement1 ps:P4797 _:anyValueP4797. ?statement1 ps:P4797 ?davalue. SERVICE wikibase:label { bd:serviceParam wikibase:language "es". } }
Listar los nacidos en una región/provincia
[edit]- Try it!
SELECT DISTINCT ?person ?personLabel ?personDescription ?placeofbirthLabel WHERE { ?person wdt:P19 ?placeofbirth. ?placeofbirth (wdt:P131*) wd:Q81802. SERVICE wikibase:label { bd:serviceParam wikibase:language "es". } }
Listar todos los nacidos en una provincia/región fallecidos en cualquier campo de concentración nazi
[edit]- Try it!
SELECT DISTINCT ?person ?personLabel ?personDescription ?placeofbirthLabel WHERE { ?person wdt:P20 [ wdt:P31 wd:Q328468 ]; wdt:P19 [ wdt:P131 wd:Q81802 ] . OPTIONAL { ?person wdt:P19 ?placeofbirth. } SERVICE wikibase:label { bd:serviceParam wikibase:language "es". } }
Listar todos los elementos en una zona geográfica con el mismo valor de propiedad
[edit]En este caso valores idénticos de INE municipality code (P772) para Galicia (Q3908):
SELECT DISTINCT ?p772 ?item1 ?item1Label ?item2 ?item2Label {
VALUES ?p131 {wd:Q3908}
?item1 wdt:P772 ?p772; wdt:P131* ?p131a .
?item2 wdt:P772 ?p772; wdt:P131* ?p131b .
FILTER(?p131a=?p131 || ?p131b=?p131)
FILTER(STR(?item1)<STR(?item2)) .
SERVICE wikibase:label { bd:serviceParam wikibase:language "es" } .
}
ORDER BY ?p772
(Source)
Truco de aceleración «rutas inversas de propiedad»
[edit]Para evitar timeouts en consultas como
- Try it!
SELECT DISTINCT ?item WHERE { ?item (wdt:P31/(wdt:P279*)) wd:Q271669; wdt:P131 wd:Q81802. }
Cito: The query is correct, but runs slowly. Using a technique described at Wikidata:SPARQL query service/query optimization#Inverse property paths you can speed up the query and avoid the timeout by reversing the property path like this:
SELECT DISTINCT ?item WHERE {
?item wdt:P131* wd:Q81802.
wd:Q271669 ^wdt:P279*/^wdt:P31 ?item.
}
(source)
Todo lo que enlaza a un elemento
[edit]todo, a lo burro, con todas las tripletas que apuntan:
SELECT ?item ?itemLabel ?P31 ?P31Label WHERE {
?item ?property wd:Q1631944 .
SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
}
lo mismo pero filtrando schema:about:
SELECT ?item ?itemLabel ?P31 ?P31Label WHERE {
?item ?property wd:Q1631944 .
MINUS { ?item schema:about wd:Q1631944 }
SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
}
y parece que este funciona exactamente igual aunque no termino de comprender el por qué:
SELECT DISTINCT ?item ?itemLabel WHERE {
?item ?property wd:Q1631944.
?item wdt:P31 ?P31.
SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
}
Obviamente se pueden añadir más condiciones a la consulta.
Y otro ejemplo que me pasan por Telegram que no sé realmente interpretar pq a esta hora estoy empanao :-)
select distinct ?item ?itemLabel {
?a ?p1 wd:Q1631944.
# ignore sitelinks
minus { ?a schema:about wd:Q1631944 }
# if ?a is a statement node (has a rank), ?p1 is a predicate like ps: or pq:
# so select triples which use the statement node as a value (?p2 is a p: predicate)
optional {
?a wikibase:rank [].
?b ?p2 ?a.
}
# if ?a is a reference node, a statement node links to it using prov:wasDerivedFrom
# again, select triples which use the statement node as a value
optional {
?c ?p3 [ prov:wasDerivedFrom ?a ].
}
# assign ?item to the first assigned value out of ?b (ps:/pq:), ?c (pr:) and ?a (wdt: and any cases not caught by the previous two)
bind (coalesce(?b, ?c, ?a) as ?item)
service wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
} order by ?itemLabel ?item
Todas las entradas del eDBA
[edit]Todas los elementos cuya described at URL (P973) apunta a la web del eDBA.
SELECT DISTINCT ?item ?itemLabel ?itemDescription ?P973 ?lugar_de_nacimiento ?lugar_de_nacimientoLabel ?fecha_de_nacimiento ?lugar_de_fallecimiento ?lugar_de_fallecimientoLabel ?fecha_de_fallecimiento ?sexo_o_g_nero ?sexo_o_g_neroLabel WHERE {
SERVICE wikibase:label { bd:serviceParam wikibase:language "es". }
?item wdt:P973 ?P973.
FILTER(CONTAINS(STR(?P973), "edba.nsf"))
OPTIONAL { ?item wdt:P19 ?lugar_de_nacimiento. }
OPTIONAL { ?item wdt:P569 ?fecha_de_nacimiento. }
OPTIONAL { ?item wdt:P20 ?lugar_de_fallecimiento. }
OPTIONAL { ?item wdt:P570 ?fecha_de_fallecimiento. }
OPTIONAL { ?item wdt:P21 ?sexo_o_g_nero. }
}
Ejemplo de optimización de consulta
[edit]Si así acabamos en timeout
SELECT ?item ?itemLabel WHERE {
?item (wdt:P131*) wd:Q5783.
wd:Q69873044 ^wdt:P1435 ?item.
FILTER NOT EXISTS { ?item wdt:P3318 ?P3318. }
}
con subselect y consejos lo resolvemos en un plis:
SELECT ?item ?itemLabel
WITH { SELECT ?item { ?item wdt:P1435 wd:Q69873044 } } AS %sub
WHERE
{
include %sub
?item wdt:P131* wd:Q5783 . hint:Prior hint:gearing "forward" .
FILTER NOT EXISTS { ?item wdt:P3318 ?P3318 }
SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en" }
}
Listados en ESwiki y ENwiki
[edit]SELECT ?MUNICIPIO ?MUNICIPIOLabel ?MUNICIPIODescription ?coordenadas ?estatus_patrimonialLabel ?ESwiki ?ENwiki WHERE {
SERVICE wikibase:label { bd:serviceParam wikibase:language "es". }
?MUNICIPIO wdt:P131 wd:Q1631944.
OPTIONAL { ?MUNICIPIO wdt:P625 ?coordenadas. }
OPTIONAL {
?ESwiki schema:about ?MUNICIPIO;
schema:isPartOf <https://es.wikipedia.org/>.
}
OPTIONAL {
?ENwiki schema:about ?MUNICIPIO;
schema:isPartOf <https://en.wikipedia.org/>.
}
OPTIONAL { ?MUNICIPIO wdt:P1435 ?estatus_patrimonial. }
}
Todos los elementos en una localización administrativa
[edit]Que usen located in the administrative territorial entity (P131) o location (P276). Ojo que es probable tenga que ser refinada.
SELECT DISTINCT ?municipio ?municipioLabel ?municipioDescription ?coordenadas ?imagen WHERE {
SERVICE wikibase:label { bd:serviceParam wikibase:language "es". }
{ ?municipio (wdt:P131*) wd:Q5277. }
UNION
{ ?municipio (wdt:P276*) wd:Q5277. }
OPTIONAL { ?municipio wdt:P625 ?coordenadas. }
OPTIONAL { ?municipio wdt:P18 ?imagen. }
}
Consulta de elementos geolocalizados alrededor de un punto predeterminado
[edit]SELECT ?place ?placeLabel ?dist (SAMPLE(?image) AS ?image)
WHERE
{
SERVICE wikibase:around {
?place wdt:P625 ?location .
bd:serviceParam wikibase:center "Point(${longitude} ${latitude})"^^geo:wktLiteral .
bd:serviceParam wikibase:radius "10" .
}
?place wdt:P1435 ?monument .
OPTIONAL { ?place wdt:P18 ?image . }
SERVICE wikibase:label { bd:serviceParam wikibase:language "${langs.map(lang => lang.code).join(',')}" }
BIND(geof:distance("Point(${longitude} ${latitude})"^^geo:wktLiteral, ?location) as ?dist)
}
GROUP BY ?place ?placeLabel ?dist
ORDER BY ?dist
Elementos geolocalizados alrededor de Alamedilla (Q1631944)
[edit]SELECT ?item ?itemLabel ?distance ?location WHERE {
wd:Q1631944 wdt:P625 ?destino.
SERVICE wikibase:around {
?item wdt:P625 ?location.
bd:serviceParam wikibase:center ?destino;
wikibase:radius "20";
wikibase:distance ?distance.
}
SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
}
Consultar los elementos que tienen determinada cadena como valor para una propiedad determinada
[edit]En este ejemplo buscamos «ourism»:
SELECT ?item ?itemLabel ?P1282 WHERE {
SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
OPTIONAL { ?item wdt:P1282 ?P1282. }
FILTER(CONTAINS(?P1282, "ourism"))
}
Todas las clases de playas alrededor de la ciudad de Almería
[edit]SELECT DISTINCT ?item ?itemLabel ?imagen (SAMPLE(?coords) AS ?coords) ?P131 ?P131Label WHERE {
wd:Q10400 wdt:P625 ?lugar.
VALUES ?clase {
wd:Q40080 wd:Q38051384 wd:Q53800413 wd:Q28060956
wd:Q28060923 wd:Q3390872 wd:Q98375039 wd:Q57409799 wd:Q35800652 wd:Q35101126
wd:Q24633899 wd:Q18751767 wd:Q17155155 wd:Q15849385 wd:Q12353867 wd:Q11959973
wd:Q11941943 wd:Q9089165 wd:Q7900097 wd:Q7493708 wd:Q6881911 wd:Q5655097
wd:Q4831654 wd:Q2892735 wd:Q1059407 wd:Q847935 wd:Q573367 wd:Q567998
}
SERVICE wikibase:around {
?item wdt:P625 ?coords.
bd:serviceParam wikibase:center ?lugar;
wikibase:radius "20".
}
{ ?item wdt:P31 ?clase. }
SERVICE wikibase:label { bd:serviceParam wikibase:language "es". }
OPTIONAL { ?item wdt:P18 ?imagen. }
OPTIONAL { ?item wdt:P131 ?P131. }
}
GROUP BY ?item ?itemLabel ?imagen ?P131 ?P131Label
Todos los artículos académicos con P31= scholarly article (Q13442814)
[edit]SELECT (COUNT(*) AS ?total) WHERE { _:b3 wdt:P31 wd:Q13442814. }
filtrar elementos por cadena de texto en la URL
[edit]# properties with equivalent in CIDOC-CRM
SELECT DISTINCT ?item ?itemLabel ?cidocURL WHERE {
?item wdt:P1628 ?cidocURL.
FILTER(REGEX(STR(?cidocURL), "cidoc-crm"))
SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
}
Filtrar por calificadores
[edit]Ejemplo con todos los municipios españoles desaparecidos:
SELECT ?item ?itemLabel WHERE {
?item (wdt:P31/(wdt:P279*)) wd:Q2074737;
p:P31 ?statement.
?statement ps:P31 ?municipio;
pq:P582 ?fechafin.
SERVICE wikibase:label { bd:serviceParam wikibase:language "es". }
}
y la variante de todos los municipios que sí existen:
SELECT DISTINCT ?item ?itemLabel ?c_digo_INE ?identificador_GeoNames WHERE {
?item (wdt:P31/(wdt:P279*)) wd:Q2074737.
FILTER(NOT EXISTS { ?item wdt:P582 ?fecha_de_fin. })
MINUS {
?item p:P31 ?statement.
?statement ps:P31 ?municipio;
pq:P582 ?fechafin.
}
MINUS { ?item wdt:P31 wd:Q55863584. }
MINUS { ?item wdt:P31 wd:Q19730508. }
SERVICE wikibase:label { bd:serviceParam wikibase:language "es". }
OPTIONAL { ?item wdt:P772 ?c_digo_INE. }
OPTIONAL { ?item wdt:P1566 ?identificador_GeoNames. }
}
Todas las obras de Rainer Werner Fassbinder (Q44426)
[edit]SELECT DISTINCT ?movie ?movieLabel ?instancia_deLabel WHERE {
SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en,de". }
VALUES ?ocupacion {
wdt:P57 wdt:P161 wdt:P58 wdt:P344 wdt:P86 wdt:P162
}
?movie ?ocupacion ?Fassbinder.
?movie wdt:P31/wdt:P279* ?obra_audiovisual.
OPTIONAL { ?movie wdt:P31 ?instancia_de. }
BIND(wd:Q44426 AS ?Fassbinder)
BIND(wd:Q2431196 AS ?obra_audiovisual)
}
ORDER BY (?movie)
Empotrar un gráfico de tarta con una plantilla
[edit]Consultar el ejemplo User:Olea/Patrimonio andaluz#Patrimonio inmueble
Extraer sitelinks y contadores
[edit]Una consulta muy compleja que robé por ahí aplicada a Listeria: Usuario:Olea/Ejemplo avanzado de Listeria.
Usando el graph builder de WDQS
[edit]Con un ejemplo no trivial que extrae calificadores de colores de las partes de un colibrí: https://w.wiki/65rq
(OjO: una especie puede tener partes con más de un color, así que aunque la tabla queda preciosa en la práctica hay colores que se sobre escriben)
![]() | Graphs are temporarily unavailable due to technical issues. |