Shortcut: Wikidata:Gentle Query

Wikidata:Serviço de consulta SPARQL/Uma introdução suave ao serviço de consulta Wikidata

From Wikidata
Jump to navigation Jump to search

Uma introdução suave ao serviço de consulta Wikidata

Já se perguntou coisas como:

  • Quais são as maiores cidades do mundo com uma prefeita mulher?
  • Que aeroportos estão localizados a 100 km de Berlin?
  • Quem foram todos os descendentes conhecidos de Genghis Khan?

Wikidata tem as respostas.

O que é o Wikidata?

Wikidata é um repositório de conhecimento. Você pode ler uma introdução à ideia e aos conceitos por trás do Wikidata na nossa pagina de introdução.

Como faço uma pergunta?

A linguagem de consulta usada para fazer perguntas como aquelas no Wikidata é chamada SPARQL. Se isto soa técnico demais e muito complicado para você, não se preocupe. Para esta introdução leve, você não terá que aprender SPARQL. Em vez disso, vamos ver exemplos de consultas que já existem e como podemos editá-las.

O que é uma consulta?

Uma consulta é uma forma especial de questão que sistemas computacionais podem entender e responder. A menos que você esteja interagindo com uma inteligência artificial, você precisará aprender a formular suas questões de um certo modo.

Posso usar livremente estes dados?

Oh, sim, Wikidata pode ser usada por qualquer um, pois toda a informação está em domínio público (CC0).

E agora?

Iniciaremos com um exemplo simples para lhe mostrar como usar este serviço, e nós continuaremos com exemplos mais elaborados, de tal modo que ao final terá a resposta às tuas perguntas. Prometemos.

Como usar Wikidata para uma consulta simples

Vamos por meio de um exemplo simples demonstrar como obter uma lista de todos os gatos conhecidos do mundo.

Obter uma lista de todos os gatos conhecidos do mundo

Use este URL para acessar o serviço de consulta: https://query.wikidata.org

  1. Clique em “Exemplos”
  2. Selecione “Gatos” na lista que aparece na nova janela
  3. Clique em “Executar” logo abaixo do bloco de código

Isto agora nos dá uma uma lista de todos os gatos famosos ou não presentes na internet - ou pelo menos daqueles que o Wikidata tem conhecimento. Isto é ótimo, já que você é aficionado por gatos e não, digamos, aficionado por cães.

E para os cachorros?

Se, ao invés, você deseja listar os cachorros (ou o que quer que seja), existem duas formas de editar sua consulta:

  1. Usar o Query Helper para mudar o item de gato para jardim zoologico:
  2. Editar manualmente a consulta cada item no Wikidata é identificado univocamente usando um código. Este código é Q146 para “gato”. Para encontrar o código correspondente a “cachorro”, Você pode procurar no Wikidata:
  1. Use a função autocompletar (o resto será escrito ao final)
  2. Comece com o exemplo de "Gato" removendo "Q146"
  3. Insira o cursor após "wd:"
  4. Escreva "Cachorro" após "wd:"
  5. Pressione ao mesmo tempo as teclas Ctrl e Espaço
  6. Use as setas para baixo e para cima e, quando pressionar a tecla Enter, o texto será substituído por Q144
    Aviso: os resultados da busca dependem do idioma da interface.
  1. Vá para https://www.wikidata.org
  2. Escreva "cachorro" no campo de buscas
  3. Clique no primeiro resultado dentre os exibidos
  4. Atente para o número do item para "cachorro" que aparece na página do Wikidata aberta (Q144)

Para alterar a consulta de "gato" para "cachorro", simplesmente mude Q146 para Q144 no editor de SPARQL.

Executar a consulta, e Wikidata exibirá uma listagem de todos os cachorros famosos da Internet (ou, ao menos, aqueles que o Wikidata conhece)

Explicando a consulta

Agora vamos analisar o código para poder generalizar e buscar um só objeto (por exemplo: cachorros, planetas, países ou canções)

#Cats
SELECT ?item ?itemLabel
WHERE
{
	?item wdt:P31 wd:Q146 . 
	SERVICE wikibase:label { bd:serviceParam wikibase:language "en" }
}
  • SELECT A consulta seleciona (select, em inglês) alguma coisa. O que exatamente você deseja selecionar e exibir é descrito mais adiante, nesta linha do código, você declara as variáveis (marcadores de posição). Neste caso, elas se chamam ?item e ?itemLabel. Você pode notar que as variáveis é sempre aquilo que for iniciado com ponto de interrogação.
  • ?item Este é a listagem de itens que você está querendo consultar. No primeiro exemplo dado, gatos são os itens a consultar. Itens no Wikidata trabalham em muitos idiomas diferentes (são quase 300 ao todo), pois são armazenados de forma que funcionem sem depender de um idioma em particular, seja o inglês ou qualquer outro. Assim, cada conceito recebe um número. Q146 é o conceito de um gato, Q64 é a cidade alemã de Berlim, Q42 é o escritor Douglas Adams e assim por diante. Dica: ?item é somente um nome de variável escolhido para usar na consulta. Qualquer outro nome poderia ser escolhido, por exemplo:
  • ?itemLabel Humanos interpretam muito melhor nomes (em uma língua humana) do que números. Um rótulo é o nome de um item numa língua humana, por exemplo inglês, esperanto, japonês, ou zulu… Assim, mostram os rótulos na consulta a fim de que Q1371145 seja identificado pelo nome “Socks” (que é o gato da família do político estadunidense Bill Clinton). Mais detalhes sobre o serviço de rótulos estão em User manual.
  • WHERE {. Esta é a cláusula WHERE ("tal que") da consulta. Ela define os valores das variáveis na consulta. Uma cláusula WHERE começa e termina com chaves, { e }.
  • wdt:P31 é o predicado do sujeito. Se passar o ponteiro sobre ele, verá a identificação do rótulo (no caso, instância de).

  • wd:Q146 é o objeto. Da mesma forma, se passar o ponteiro sobre ele, verá a identificação do rótulo (no caso, gato).

Tudo isso pode parecer bastante texto! Talvez seja mais fácil expressar a consulta numa linguagem mais natural:

“Exiba uma listagem de itens e seus rótulos, tal que os itens sejam instâncias de gato. Gere os rótulos desses itens em português.”

Com o código que usamos nesse exemplo de gato, surge uma listagem de gatos famosos na Internet. Esta consulta pode ser alterada facilmente para mostrar, por exemplo, uma listagem similar de cachorros.

Passo-a-passo de converter texto em SPARQL

As animações abaixo mostram como escrever em linguagem natural e converter o texto em consultas no editor de SPARQL.

O importante é prefixar as variáveis com ?, os itens com wd: a as propriedades com wdt:, e usar o atalho das teclas Ctrl e espaço (ou Ctrl+Alt+espaço ou Alt+espaço) para ativar a função de autocompletar que converte os itens e propriedades nos nomes dados no Wikidata.

Mergulho na interface gráfica

Como alterar a língua dos resultados exibidos na consulta?

With this search query tool, you can not only customise and search for simple or aggregated, compound, nested and complex queries but you can also search in ANY language and get results in ANY language too.

  • Change the default language code from “en” (English) to any other language code, say “ja” for Japanese.
#Cats  
SELECT ?item ?itemLabel WHERE
{
     ?item wdt:P31 wd:Q146 .
     SERVICE wikibase:label { bd:serviceParam wikibase:language "ja" }
}

Como alterar a ordem dos resultados?

The order of the items displayed can be easily changed in the interface. Just click on the relevant columns of the search results to customise the sorting order:

Como alterar a língua na interface gráfica?

Clique na palavra "English" para selecionar a língua que deseja utilizar:

Note que a interface gráfica altera para a língua selecionada:

Mas e as fotos de gatos? Como buscar por imagens?

Até agora, os resultados das consultas foram exibidos em formato de tabela. Experimente buscar por imagens:

Click the “Examples” button and select the “Even more cats, with pictures” example. Run the query and cat images should pop up at the lower half of the screen.

This is what displays the result as images instead of a table. You can manually switch how the data is displayed by using the “Display” menu in the lower right corner of the result. Try switching the menu to “Table” to see the same result in a table view.

Let’s have a look at what’s new in the query, compared to the query in the previous chapter. Written in plain English, the query would read “Give me all items that have something to do with cats. Also give me the image for each item. And by the way, display the result as a grid of images, not as a table.”

  • #defaultView:ImageGrid What looks like a comment, is actually an instruction to display the query result as images instead of a table.
  • ?x1 This means that we query for any predicate, not only for “is an instance of”. Think of predicates like “depicts” (P180) or “is named after” (P138). We are not using ?x1 anywhere else in the query, meaning the placeholder stands for “I don’t care what the predicate is, give me all results that somehow have a cat as the subject”
  • OPTIONAL Inside the curly braces you see another statement that adds optional data to the result. The placeholder ?item is reused and coupled with the predicate P18 (meaning “(has) image” and a new placeholder ?pic. Wrapping the statement with OPTIONAL means that items do not necessarily have to have a P18 predicate to show up in the list and that the ?pic placeholder can be empty.

Try modifying the query:

  • Search for dogs instead of cats. Hint: Change the Object part of the first statement in WHERE.
  • Only show items that “depict” cats (you’ll get paintings). Hint: replace ?x1 with something else.
  • Remove the OPTIONAL

There are other ways to show your data, but not all of them are always applicable, which is why some are greyed out in the menu. “Image map” is only selectable if the result data actually contains image URLs. In one of the following chapters you’ll learn how to display items as points on a map.

Como compartilhar uma consulta obtida?

If you want to share your query with someone else – say, on social media – you can create a short link for your query.

  • Complete your query
  • Click the LINK icon:
  • Copy the URL listed there. This is the URL for the query.

Busca em mapas

There are more ways to visualize the query results. If the query asks for geocoordinates, the results can be displayed on a map.

Look at this example of lighthouses in Norway. When you run the query, you’ll see red dots that mark the location of lighthouses on the Norwegian coast.


Use a caixa de diálogo para explorar

Once the results of a query have loaded, you can see a magnifying glass icon on each result.

Clicking this icon opens the Explorer Dialog.

The explorer dialog by default, displays a single node representing that particular result. Below the node, you can see a toggle that defaults to ‘Outgoing’.

This means that clicking on any node will expand all the properties of that node, from the entire Wikidata knowledge base. Toggling this to ‘Incoming’ allows you to see all the incoming links or properties that point to the node. This is a way to explore all the relationships between the various items and their properties using Wikidata.

You can open multiple explorer dialogs at once, allowing you to compare the results of more than one query at once.

The explorer dialog also has a toolbar at the bottom right corner which is used to switch between multiple views like Graph, Tree, Map, Table etc.

There are more visualizations for you to explore:

Look through the query examples and try them out!

Função autocompletar

In the editor, you can press Ctrl+Space at any point in the query and get suggestions for code that might be appropriate; select the right suggestion with the up/down arrow keys, and press Enter to select it.

For example, instead of writing out SERVICE wikibase:label { bd:serviceParam wikibase:language "en". } every time, you can just type SERV, hit Ctrl+Space, and the first suggestion will be that complete label service incantation, ready for use! Just hit Enter to accept it. (The formatting will be a bit different, but that doesn’t matter.)

And autocompletion can also search for you. If you type one of the Wikidata prefixes, like wd: or wdt:, and then just write text afterwards, Ctrl+Space will search for that text on Wikidata and suggest results. wd: searches for items, wdt: for properties. For example, instead of looking up the items for Johann Sebastian Bach (Q1339) and father (P22), you can just type wd:Bach and wdt:fath and then just select the right entry from the autocompletion. (This even works with spaces in the text, e. g. wd:Johann Sebastian Bach.)

NB: For ChromeOS and MacOS users: the shortcuts Ctrl+Alt+Space and Alt+Enter should also work.

Como seguir a partir daqui?

You can probably find your way around the Wikidata Query Service now. Exploring the interface and changing values in the queries can be a good way to learn how to ask your own questions on Wikidata.