User:PAC2/SPARQL queries

Home

Cette page est un aide-mémoire personnel pour mes requêtes SPARQL.

J'utilise évidemment query.wikidata.org pour faire mes requêtes. Si je veux aller plus loin, j'utilise aussi l'outil Wikidata:PAWS qui permet d'avoir des notebooks SPARQL (voir par exemple requêtes sur la diversité de genre). J'utilise Observablehq pour explorer les données de Wikidata directement en Javascript.

Pour me documenter, j'utilise wikibook SPARQL, le tutorial SPARQL de Wikidata et le manuel SPARQL de MediaWiki. La page MediaWiki sur l'optimisation des requêtes est aussi très utile.

Récupérer les labels, les descriptions et les alias edit

Récupérer les labels edit

Pour obtenir, les libellés, on peut utilise le service wikibase:label ou l'espace rdfs:label.

Avec la méthode rdfs:label :

The following query uses these:

Avec la méthode wikibase:label

The following query uses these:

Exemples edit

Liste des éléments avec le même label edit

The following query uses these:

  • Properties: instance of (P31)     
    #title:Entities with same label
    SELECT ?item ?itemLabel ?itemDescription ?nature ?natureLabel
    WHERE {
    wd:Q90 rdfs:label ?itemLabel filter (lang(?itemLabel) = "[AUTO_LANGUAGE]").
    ?item rdfs:label ?itemLabel.
    OPTIONAL{
    ?item schema:description ?itemDescription filter (lang(?itemDescription) = "[AUTO_LANGUAGE]").
    }
    ?item wdt:P31 ?nature.
    ?nature rdfs:label ?natureLabel filter (lang(?natureLabel) = "[AUTO_LANGUAGE]").
    }
    ORDER BY ?nature ?natureLabel
    

Récupérer les alias et les descriptions edit

On peut récupérer les descriptions et les alias avec la méthode wikibase:label.

The following query uses these:

  • Properties: given name (P735)     
    SELECT ?item ?itemLabel ?itemDescription ?itemAltLabel  WHERE {
      SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE]". }
      ?item wdt:P735 wd:Q346047.
    }
    

Récupérer les éléments appartenant à une sous-classe edit

The following query uses these:

  • Properties: subclass of (P279)     , instance of (P31)     
    SELECT ?item ?itemLabel WHERE  {
      SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
      wd:Q1172284 ^wdt:P279*/^wdt:P31 ?item.
    }
    LIMIT 100
    

Classer les éléments par nombre de liens de site edit

The following query uses these:

  • Properties: given name (P735)     
    SELECT ?item ?itemLabel ?itemDescription ?sitelinks WHERE {
      SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE]". }
      ?item wikibase:sitelinks ?sitelinks.
      ?item wdt:P735 wd:Q346047.
    }
    ORDER BY DESC(?sitelinks)
    

Obtenir la liste des éléments sans une propriété edit

L'instruction MINUS permet d'obtenir la liste des éléments qui n'ont pas une propriété.

La requête ci-dessous permet de récupérer la liste des éléments ayant un data.gouv.fr organisation ID (P3206) sans avoir de déclaration instance of (P31).

The following query uses these:

  • Properties: data.gouv.fr organisation ID (P3206)     , instance of (P31)     
    SELECT DISTINCT ?datagouvid ?item ?itemLabel ?nature_of
    WHERE {
      ?item wdt:P3206 ?datagouvid .
      MINUS{ ?item wdt:P31 ?nature_of. }  
      SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE]" }
      }
    ORDER BY ?itemLabel
    

Récupérer la liste des éléments à partir d'identifiants externes edit

La requête ci dessous permet de récupérer la liste des éléments Wikidata à partir de l'X username (P2002).

The following query uses these:

  • Properties: X username (P2002)     
    SELECT ?string ?item ?itemLabel WHERE {
      VALUES ?string {
        "EmmanuelMacron"
        "realDonaldTrump"
      }
      ?item wdt:P2002 ?string.
      SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE]" }
    }
    ORDER BY ?itemLabel
    

Récupérer la liste des éléments à partir d'une liste de noms de pages Wikipédia edit

The following query uses these:

SELECT DISTINCT ?string ?item ?itemLabel WHERE {
  VALUES ?string {
    "Paris"@fr
    "Meudon"@fr
    "Bellevue (quartier de Meudon)"@fr
  }
  ?sitelink schema:about ?item;
    schema:isPartOf <https://fr.wikipedia.org/>;
    schema:name ?string.
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE]" }
}
ORDER BY ?itemLabel

Obtenir la liste des déclarations sur un élément edit

La requête ci-dessous récupère la liste des déclarations sur la page de Meudon (Q234735).

The following query uses these:

  • Items: Meudon (Q234735)     
    SELECT DISTINCT ?itemLabel ?wd ?wdLabel ?ps_ ?ps_Label {
      VALUES ?item {wd:Q234735}
      ?item ?p ?statement .
      ?statement ?ps ?ps_ . 
      ?wd wikibase:claim ?p.
      ?wd wikibase:statementProperty ?ps.
      SERVICE wikibase:label { bd:serviceParam wikibase:language "fr" }
    } ORDER BY ?wdLabel
    

La requête ci-dessous ajoute aussi les qualifications associées aux déclarations.

SELECT DISTINCT ?itemLabel ?wd ?wdLabel ?ps_ ?ps_Label ?wdpqLabel ?pq_Label {
  VALUES ?item {wd:Q234735}
  ?item ?p ?statement .
  ?statement ?ps ?ps_ . 
  ?wd wikibase:claim ?p.
  ?wd wikibase:statementProperty ?ps.
  OPTIONAL {
  ?statement ?pq ?pq_ .
  ?wdpq wikibase:qualifier ?pq .
  }
  SERVICE wikibase:label { bd:serviceParam wikibase:language "fr" }
} ORDER BY ?wdLabel
Try it!

Obtenir la liste des déclarations concernant un élément edit

La requête suivante permet de récupérer toutes les déclarations concernant Meudon (Q234735) sur les autres pages de Wikidata.

SELECT DISTINCT ?item ?itemLabel ?propertyLabel ?targetLabel  WHERE {
  VALUES ?target {
    wd:Q234735
  }
  ?item ?p ?statement.
  ?statement ?ps ?target.
  ?property wikibase:claim ?p;
    wikibase:statementProperty ?ps.
  SERVICE wikibase:label { bd:serviceParam wikibase:language "fr". }
}
ORDER BY (?targetLabel) (?propertyLabel) (?itemLabel)
Try it!

Compte des déclarations sur un élément par propriété edit

SELECT  ?propertyLabel ?targetLabel (COUNT(?item) AS ?count) WHERE {
  VALUES ?target {
    wd:Q234735
  }
  ?item ?p ?statement.
  ?statement ?ps ?target.
  ?property wikibase:claim ?p;
    wikibase:statementProperty ?ps.
  SERVICE wikibase:label { bd:serviceParam wikibase:language "fr". }
}
GROUP BY ?targetLabel ?propertyLabel
ORDER BY DESC(?count)
Try it!

Explorer une hiérarchie edit

Obtenir la liste des sous-classe d'un élément edit

La requête ci-dessous permet d'obtenir la liste des sous-classes de decentralized service of the State (Q28070878) avec une indication de la distance entre les deux éléments.

The following query uses these:

  • Properties: subclass of (P279)     
    SELECT ?item ?itemLabel ?sousclasse ?sousclasseLabel (count(?mid) as ?distance) { 
      BIND(wd:Q28070878 as ?item)
      ?mid wdt:P279* ?item .
      ?sousclasse wdt:P279+ ?mid .
      SERVICE wikibase:label { bd:serviceParam wikibase:language "fr". }
    }
    GROUP BY ?item ?itemLabel ?sousclasse ?sousclasseLabel 
    ORDER BY ?itemLabel ?distance ?sousclasseLabel
    

Visualiser une hiérarchie edit

Cette requête permet d'obtenir la liste des sous-classes de decentralized service of the State (Q28070878) avec le niveau. Je n'ai pas trouvé de manière de le faire de manière récursive.

#defaultView:Tree
SELECT ?super ?superLabel ?level1 ?level1Label ?level2 ?level2Label ?level3 ?level3Label ?level4 ?level4Label WHERE {
  BIND(wd:Q28070878 AS ?super)
  ?level1 wdt:P279 ?super.
  OPTIONAL {
    ?level2 wdt:P279 ?level1.
    OPTIONAL {
      ?level3 wdt:P279 ?level2.
      OPTIONAL { ?level4 wdt:P279 ?level3. }
    }
  }
  SERVICE wikibase:label { bd:serviceParam wikibase:language "fr". }
}
ORDER BY ?superLabel
Try it!

Compter des éléments avec une hiérarchie edit

Compter des éléments par nature (instance of (P31)) est trompeur parce qu'on ne voit pas que certaines occurrences sont des sous-classes (subclass of (P279)) les unes des autres.

L'idée c'est d'avoir un processus en deux étapes avec deux requêtes SELECT.

SELECT  ?category ?categoryLabel (COUNT (?item) as ?count) WHERE {
  SELECT DISTINCT ?item ?category ?categoryLabel WHERE {
  VALUES ?category {
    wd:Q484170
    wd:Q2659904
    wd:Q163740
  }
  ?item wdt:P31 ?instance_of;
    wdt:P3206 ?datagouvid.
  ?instance_of (wdt:P279*) ?category.
  SERVICE wikibase:label { bd:serviceParam wikibase:language "fr". }
}
}
GROUP BY ?category ?categoryLabel
ORDER BY DESC(?count)
Try it!

Combiner des requêtes edit

SELECT ?count ?description
WITH {
  SELECT (COUNT(*) AS ?count) WHERE { [] wdt:P3206 [] . }
} AS %datagouvid
WITH {
  SELECT (COUNT(*) AS ?count) WHERE { 
    ?item wdt:P3206 [] ; 
          wdt:P1616 [].
  }
} AS %siren
WITH {
  SELECT (COUNT(*) AS ?count) WHERE { 
    ?item wdt:P3206 [] ; 
          wdt:P6671 [].
  }
} AS %annuaire
WHERE {
  {
    INCLUDE %datagouvid
    BIND("éléments avec un identifiant datagouv" AS ?description)
  }
  UNION
  {
    INCLUDE %siren
    BIND("éléments avec un identifiant datagouv et un identifiant siren" AS ?description)
  }
  UNION
  {
    INCLUDE %annuaire
    BIND("éléments avec un identifiant datagouv et un identifiant de l'annuaire du service public" AS ?description)
  }
}
ORDER BY DESC(?count)
Try it!

Travailler avec les unités edit

#title: Longest rivers in the France
SELECT DISTINCT ?item ?itemLabel ?length ?unit ?unitLabel WHERE {
  ?item (wdt:P31/(wdt:P279*)) wd:Q55659167;
    wdt:P17 wd:Q142;
    p:P2043 ?stmnode.
  ?stmnode psv:P2043 ?valuenode.
  ?valuenode wikibase:quantityAmount ?length;
    wikibase:quantityUnit ?unit.
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE], en". }
}
ORDER BY DESC (?length)
LIMIT 100
Longest rivers in the France
#title: Longest rivers in the France
SELECT DISTINCT ?item ?itemLabel ?length ?unit ?unitLabel ?length_in_m WHERE {
  ?item (wdt:P31/(wdt:P279*)) wd:Q55659167;
    wdt:P17 wd:Q142;
    p:P2043 ?stmnode.
  ?stmnode psv:P2043 ?valuenode.
  ?valuenode wikibase:quantityAmount ?length;
    wikibase:quantityUnit ?unit.
  
    # conversion to SI unit
  ?unit          p:P2370                 ?unitstmnode.   # conversion to SI unit
  ?unitstmnode   psv:P2370               ?unitvaluenode. 
  ?unitvaluenode wikibase:quantityAmount ?conversion.
  ?unitvaluenode wikibase:quantityUnit   wd:Q11573.      # meter
  BIND(?length * ?conversion AS ?length_in_m).
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE], en". }
}
ORDER BY DESC (?length_in_m)
LIMIT 100
Longest rivers in the France

Utiliser l'API MediaWiki edit

Récupérer le genre des membres d'une catégorie sur Wikipédia edit

Requête découverte dans le bulletin hebdomadaire du 15 février 2021 grâce au partage de Ainali.

#Using mwapi to base a query on articles in a Wikipedia category
# Use the MediaWiki API to get the articles from a specific category in a specific Wikipedia language version.
# Then use this results as usual in a query, in this example a simple query for the gender.
# By User:Ainali with the help of User:Dipsacus fullonum  2021-02
SELECT ?item ?itemLabel ?genderLabel WHERE {
  SERVICE wikibase:mwapi {
     bd:serviceParam wikibase:endpoint "fr.wikipedia.org";     # Set the project here
                     wikibase:api "Generator";
                     mwapi:generator "categorymembers";        # Selects the content from a category
                     mwapi:gcmtitle "Catégorie:Sociologue français";.    # Specifies the category (Born in 2001)
     ?item wikibase:apiOutputItem mwapi:item.
  } 
  FILTER BOUND (?item)                                         # Safeguard to not get a timeout from unbound items when using ?item below
  ?item wdt:P21 ?gender .                                      # Example retrieval of a value
SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }    
}
Try it!

Récupérer les liens genrés d'une page edit

The following query uses these:

  • Properties: sex or gender (P21)     
    SELECT ?item ?itemLabel ?genderLabel WHERE {
      SERVICE wikibase:mwapi {
         bd:serviceParam wikibase:endpoint "fr.wikipedia.org";     # Set the project here
                         wikibase:api "Generator";
                         mwapi:generator "links";
                         mwapi:titles "Sociologie";. 
         ?item wikibase:apiOutputItem mwapi:item.
      } 
      FILTER BOUND (?item)                                       
      ?item wdt:P21 ?gender .                                   
    SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }    
    }
    

Compteur de liens de genres par article edit

SELECT ?gender ?genderLabel (COUNT(*) AS ?count) 
WHERE {
  SERVICE wikibase:mwapi {
     bd:serviceParam wikibase:endpoint "fr.wikipedia.org"; 
                     wikibase:api "Generator";
                     mwapi:generator "links"; 
                     mwapi:titles "Sociologie";. 
     ?item wikibase:apiOutputItem mwapi:item.
  } 
  FILTER BOUND (?item)                                         # Safeguard to not get a timeout from unbound items when using ?item below
  ?item wdt:P21 ?gender .                                  
SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }    
}
GROUP BY ?gender ?genderLabel
Try it!

Compteur de liens pour plusieurs articles edit

SELECT ?article ?gender ?genderLabel (COUNT(?item) AS ?count) 
WHERE {
  VALUES ?article { 
    "Sociologie"
    "Économie (discipline)"
    "Philosophie"
  }
  SERVICE wikibase:mwapi {
     bd:serviceParam wikibase:endpoint "fr.wikipedia.org"; 
                     wikibase:api "Generator";
                     mwapi:generator "links"; 
                     mwapi:titles ?article ;. 
     ?item wikibase:apiOutputItem mwapi:item.
  } 
  FILTER BOUND (?item)                                         # Safeguard to not get a timeout from unbound items when using ?item below
  ?item wdt:P21 ?gender .                                  
SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }    
}
GROUP BY ?article ?gender ?genderLabel
Try it!

Récupérer la liste des éléments non cités dans un article edit

The following query uses these:

  • Properties: occupation (P106)     
    SELECT ?item ?itemLabel ?sitelinks WHERE {
      SERVICE wikibase:label { bd:serviceParam wikibase:language "fr". }
      wd:Q2306091 ^wdt:P106 ?item.
      ?item wikibase:sitelinks ?sitelinks.
      FILTER NOT EXISTS {
        SERVICE wikibase:mwapi {
         bd:serviceParam wikibase:endpoint "fr.wikipedia.org";     # Set the project here
                         wikibase:api "Generator";             mwapi:generator "links";
                         mwapi:titles "Sociologue";. 
         ?item wikibase:apiOutputItem mwapi:item.
      } 
      } 
    }
    ORDER BY DESC(?sitelinks)
    LIMIT 10
    

Liste des éléments créés edit

requête inspirée de User:Jarekt/queries#My_items_without_P31. à creuser

SELECT ?item ?itemLabel ?created
{ 
  SERVICE wikibase:mwapi
  {
    bd:serviceParam wikibase:endpoint "www.wikidata.org" .
    bd:serviceParam wikibase:api "Generator" .
    bd:serviceParam mwapi:generator "random" .
    bd:serviceParam mwapi:list "usercontribs" . 
    bd:serviceParam mwapi:ucuser "PAC2" . 
    bd:serviceParam mwapi:ucprop "title|timestamp|comment" .
    bd:serviceParam mwapi:ucnamespace "0" .
    bd:serviceParam mwapi:ucshow "new" .
    bd:serviceParam mwapi:uclimit "1" .
    ?created wikibase:apiOutput "//api/query/usercontribs/item/@timestamp" .
    ?comment wikibase:apiOutput "//api/query/usercontribs/item/@comment" .
    ?item wikibase:apiOutputItem "//api/query/usercontribs/item/@title" .
    bd:serviceParam wikibase:limitContinuations "249" .
  }
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en" }
}
ORDER BY DESC(?created)
Try it!

Créer l'url de requête dans un service edit

SELECT DISTINCT * WHERE {
  ?item (wdt:P31/(wdt:P279*)) wd:Q6881511;
    wdt:P17 wd:Q142;
    rdfs:label ?itemLabel;
    wikibase:sitelinks ?sitelinks;
    wdt:P159 ?siege.
  ?siege rdfs:label ?siegeLabel.
  FILTER((LANG(?itemLabel)) = "fr")
  FILTER((LANG(?siegeLabel)) = "fr")
  MINUS { ?item wdt:P576 _:b10. }
  MINUS { ?item wdt:P1616 _:b11. }
  BIND(URI(CONCAT(" https://annuaire-entreprises.data.gouv.fr/rechercher?terme=", ENCODE_FOR_URI(?itemLabel))) AS ?search)
}
ORDER BY DESC (?sitelinks)
Try it!
SELECT DISTINCT ?item ?itemLabel ?itemDescription ?siegeLabel ?secteurLabel ?search WHERE {
  ?item (wdt:P31/(wdt:P279*)) wd:Q6881511;
    wdt:P17 wd:Q142;
    rdfs:label ?itemLabel;
    wikibase:sitelinks ?sitelinks.
  FILTER((LANG(?itemLabel)) = "fr")
  OPTIONAL { ?item wdt:P159 ?siege. }
  OPTIONAL { ?item wdt:P452 ?secteur. }
  MINUS { ?item wdt:P576 _:b10. }
  MINUS { ?item wdt:P1616 _:b11. }
  BIND(URI(CONCAT(" https://annuaire-entreprises.data.gouv.fr/rechercher?terme=", ENCODE_FOR_URI(?itemLabel))) AS ?search)
  SERVICE wikibase:label { bd:serviceParam wikibase:language "fr". }
}
ORDER BY DESC (?sitelinks)
Try it!

Requêter les propriétés edit

La requête suivante permet de récupérer la liste des propriétés associées à body of water (Q15324).

The following query uses these:

  • Properties: Wikidata item of this property (P1629)     
    SELECT ?property ?propertyLabel WHERE {
      ?property wdt:P1629 wd:Q15324.
      SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
    }
    

La requête suivante récupère toutes les propriétés qui s'appliquent aux éléments de nature subject type constraint (Q21503250).

The following query uses these:

La requête suivante permet de récupérer la liste des propriétés dont la valeur est un objet de classe geographical feature (Q618123).

The following query uses these:

Liste des propriétés qui ont pour valeur des instances ou des sous classés d'organisation edit

The following query uses these:

  • Properties: property constraint (P2302)     , class (P2308)     , relation (P2309)     
    #title: List of properties which have instances or subclass of organisations as possible value 
    SELECT ?property ?propertyLabel ?relation ?relationLabel WHERE {
      ?property p:P2302 ?statement.
      ?statement ps:P2302 wd:Q21510865;
        pq:P2308 wd:Q43229;
        pq:P2309 ?relation. 
      SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
    }
    

Liste des classes utilisées comme contraintes de valeur sur les propriétés edit

The following query uses these:

  • Properties: property constraint (P2302)     , class (P2308)     , relation (P2309)     
    #title: List of classes which are used as value constraints for the properties 
    SELECT ?class ?classLabel (COUNT(*) AS ?count) WHERE {
      ?property p:P2302 ?statement.
      ?statement ps:P2302 wd:Q21510865;
        pq:P2308 ?class ;
        pq:P2309 [] . 
      SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
    }
    GROUP BY ?class ?classLabel
    ORDER BY DESC(?count)
    

Requêtes sur les références edit

La requête suivante liste l'ensemble des statements avec pour référence affirmé dans Mediapart.

SELECT ?subject ?subjectLabel ?property ?propertyLabel ?object ?objectLabel WHERE {
  hint:Query hint:optimizer "None".
  ?ref pr:P248 wd:Q619342.
  ?statement prov:wasDerivedFrom ?ref.
  ?subject ?p ?statement.
  ?property wikibase:claim ?p;
    wikibase:statementProperty ?ps.
  ?statement ?ps ?object.
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE], en". }
}
Try it!

Tester des hypothèses edit

ASK permet de tester des hypothèses. Par exemple, on peut se demander si business (Q4830453) est une sous classe de enterprise (Q6881511).

The following query uses these:

The following query uses these:

Voir aussi edit