Вікідані:Доступ до даних

This page is a translated version of the page Wikidata:Data access and the translation is 58% complete.

Зараз Вікідані містять понад 100 мільйонів елементів і понад 650 000 лексем, і ці цифри продовжуватимуть зростати. Існує багато доступних методів доступу до всіх цих даних — цей документ викладає їх і допомагає потенційним користувачам вибрати найкращий метод відповідно до їхніх потреб.

Дуже важливо вибрати метод доступу, який надає вам потрібні дані найшвидшим та найефективнішим способом, без непотрібного навантаження на Вікідані; ця сторінка тут, щоб допомогти вам здійснити цей вибір.

Перш ніж ми почнемо

Використання даних Вікіданих

 
Наш логотип

Вікідані надають широке різноманіття загальних даних про все на світі. Усі ці дані ліцензовано CC0 як суспільне надбання — "Права не охороняються".

Зміни API та інших методів доступу до Вікіданих, регулюються Політикою стабільності інтерфейсу. Джерела даних, згадані на цій сторінці, не гарантуються як стабільні інтерфейси.

Проєкти Вікімедіа

Цей документ стосується доступу до даних із зовнішніх проектів Вікімедіа. Якщо вам треба представити дані з Вікіданих в іншому проекті Вікімедіа, де можна використовувати функції парсера, Lua та/або інші цілковито внутрішні методи, зверніться до Як використовувати дані в проектах Вікімедіа.

Найкращі методи роботи з даними

 
Вікідані створюють волонтери, такі ж люди як і ви!

Ми надаємо дані з Вікіданих вільно та без вимог щодо авторства відповідно до CC-0. Натомість ми будемо дуже вдячні, якщо у своєму проекті ви згадаєте Вікідані як джерело даних. Таким чином ви сприятимете тому, що Вікідані залишатимуться тривалий час, щоб надавати актуальні та високоякісні дані. Ми також рекламуємо найкращі проекти, які використовують дані Вікіданих.

Some examples for attributing Wikidata: "Powered by Wikidata", "Powered by Wikidata data", "Powered by the magic of Wikidata", "Using Wikidata data", "With data from Wikidata", "Data from Wikidata", "Source: Wikidata", "Including data from Wikidata" and so forth. You can also use one of our ready-made files.

Ви можете використовувати логотип Вікіданих, наведений вище, але при цьому ви не повинні створювати враження схвалення Вікіданими або Фондом Вікімедіа.

Будь ласка, запропонуйте своїм користувачам спосіб повідомити про проблеми з даними та знайти спосіб передати їх до спільноти редакторів Вікіданих, наприклад, через Пошук невідповідностей. Будь ласка, повідомте місце, де ви збираєте ці проблеми в чаті проєкту.

Найкращі методи доступу

When accessing Wikidata's data, observe the following best practices:

  • Follow the User-Agent policy – send a good User-Agent header.
  • Follow the robot policy: send Accept-Encoding: gzip,deflate and don’t make too many requests at once.
  • If you get a 429 Too Many Requests response, stop sending further requests for a while (see the Retry-After response header)
  • When available (such as with the Wikidata Query Service), set the lowest timeout that makes sense for your data.
  • When using the MediaWiki Action API, make liberal use of the maxlag parameter and consult the rest of the guidelines laid out in API:Etiquette.

Пошук

Що це?

Wikidata offers an Elasticsearch index for traditional searches through its data: Special:Search

Коли це використовувати?

Use search when you need to look for a text string, or when you know the names of the entities you're looking for but not the exact entities themselves. It's also suitable for cases in which you can specify your search based on some very simple relations in the data.

Don't use search when the relations in your data are better described as complex.

Подробиці

You can make your search more powerful with these additional keywords specific to Wikidata: haswbstatement, inlabel, wbstatementquantity, hasdescription, haslabel. This search functionality is documented on the CirrusSearch extension page. It also has its own API action.

Інтерфейс зв'язаних даних (Linked Data Interface, URI)

Що це?

Інтерфейс зв'язаних даних надає доступ до окремих сутностей через URI: http://www.wikidata.org/entity/Q???

Коли його використовувати?

Use the Linked Data Interface when you need to obtain individual, complete entities that are already known to you.

Don't use it when you're not clear on which entities you need – first try searching or querying. It's also not suitable for requesting large quantities of data.

Подробиці

 
Зустрічайте Q42

Кожен елемент або властивість має постійний URI, що складається з простору назв Вікіданих та ідентифікатора елемента або властивості (наприклад, Q42, P31), а також URL конкретних даних, до яких може отримати доступ цей елемент або властивість.

Простір назв для даних Вікіданих про сутності — https://wikidata.org/wiki/Special:EntityData.

Додавання ідентифікатора сутності до цього префіксу (ви можете використовувати /entity/ для скорочення) створює абстрактну (нейтральний формат) форму URL-адреси даних сутності. Під час доступу до ресурсу в просторі назв Special:EntityData, спеціальна сторінка застосовує узгодження вмісту для визначення формату виводу. Якщо ви відкриєте ресурс у веб-браузері, ви побачите HTML-сторінку з даними про сутність, оскільки веб-браузер надає перевагу HTML-коду. Натомість клієнти зв’язаних даних отримуватимуть дані про сутність у форматі, наприклад, JSON або RDF — незалежно від того, що вказує клієнт у своєму заголовку HTTP Accept:.

Наприклад, візьміть цей URI поняття для Дугласа Адамса — це посилання на реальну людину, а не на конкретний опис у Вікіданих:
http://www.wikidata.org/entity/Q42
Як людина з очима та браузером, ви, ймовірно, захочете отримати доступ до даних про Дугласа Адамса, використовуючи URI поняття як URL. Це запускає перенаправлення HTTP та перенаправляє клієнта на URL-адресу даних, яка містить дані Wikidata про Дугласа Адамса: https://www.wikidata.org/wiki/Special:EntityData/Q42.

Коли вам потрібно обійти узгодження вмісту, скажімо, для перегляду у веб-браузері вмісту, що відрізняється від HTML, ви можете вказати формат даних об’єкта, додавши відповідне розширення до URL-адреси даних; приклади включають .json, .rdf, .ttl, .nt або .jsonld. Наприклад, https://www.wikidata.org/wiki/Special:EntityData/Q42.json дає вам елемент Q42 у форматі JSON.

Скорочене виведення RDF

За умовчанням дані RDF, які повертає інтерфейс зв’язаних даних, мають бути повними, тому містять описи інших об’єктів, на які вони посилаються. Якщо ви хочете виключити цю інформацію, ви можете додати параметр запиту ?flavor=dump до URL-адрес, які ви запитуєте.

Додавши &flavor до URL-адреси, ви можете точно контролювати, які дані повертаються.

  • ?flavor=dump: Виключає описи сутностей, про які йдеться в даних.
  • ?flavor=simple: Provides only truthy statements (best-ranked statements without qualifiers or references), along with sitelinks and version information.
  • ?flavor=full (default): An argument of "full" returns all data. (You don't need to specify this because it's the default.)

If you want a deeper insight into exactly what each option entails, you can take a peek into the source code.

Revisions and caching

You can request specific revisions of an entity with the revision query parameter: https://www.wikidata.org/wiki/Special:EntityData/Q42.json?revision=112.

The following URL formats are used by the user interface and by the query service updater, respectively, so if you use one of the same URL formats there’s a good chance you’ll get faster (cached) responses:

Wikidata Query Service

Що це?

The Wikidata Query Service (WDQS) is Wikidata's own SPARQL endpoint. It returns the results of queries made in the SPARQL query language: https://query.wikidata.org

Коли це використовувати?

Use WDQS when you know only the characteristics of your desired data.

Don't use WDQS for performing text or fuzzy search – FILTER(REGEX(...)) is an antipattern. (Use search in such cases.)

WDQS is also not suitable when your desired data is likely to be large, a substantial percentage of all Wikidata's data. (Consider using a dump in such cases.)

Подробиці

Ви можете запитувати дані у Вікіданих через нашу точку доступу SPARQL, Службу запитів Вікіданих. Послугу можна використовувати як інтерактивний веб-інтерфейс, так і програмно, подаючи запити GET або POST на https://query.wikidata.org/sparql.

The query service is best used when your intended result set is scoped narrowly, i.e., when you have a query you're pretty sure already specifies your resulting data set accurately. If your idea of the result set is less well defined, then the kind of work you'll be doing against the query service will more resemble a search; frequently you'll first need to do this kind of search-related work to sharpen up your query. See the Search section.

Точка доступу Linked Data Fragments

Що це?

The Linked Data Fragments (LDF) endpoint is a more experimental method of accessing Wikidata's data by specifying patterns in triples: https://query.wikidata.org/bigdata/ldf. Computation occurs primarily on the client side.

Коли це використовувати?

Use the LDF endpoint when you can define the data you're looking for using triple patterns, and when your result set is likely to be fairly large. The endpoint is good to use when you have significant computational power at your disposal.

Since it's experimental, don't use the LDF endpoint if you need an absolutely stable endpoint or a rigorously complete result set. And as mentioned before, only use it if you have sufficient computational power, as the LDF endpoint offloads computation to the client side.

Подробиці

If you have partial information about what you're looking for, such as when you have two out of three components of your triple(s), you may find what you're looking for by using the Linked Data Fragments interface at https://query.wikidata.org/bigdata/ldf. See the user manual and community pages for more information.

Wikibase REST API

Що це?

The Wikibase REST API is an OpenAPI-based interface that allows users to interact with, retrieve and edit items and statements on Wikibase instances – including of course Wikidata: Wikidata REST API

Коли це використовувати?

The Wikibase REST API is still under development, but for Wikidata it's intended to functionally replace the Action API as it's a dedicated interface made just for Wikibase/Wikidata.

The use cases for the Action API apply to the Wikibase REST API as well. Use it when your work involves:

  • Редагування Вікіданих
  • Getting direct data about entities themselves

Don't use the Wikibase REST API when your result set is likely to be large. (Consider using a dump in such cases.)

It's better not to use the Wikibase REST API when you'll need to further narrow the result of your API request. In such cases it's better to frame your work as a search (for Elasticsearch) or a query (for WDQS).

Подробиці

The Wikibase REST API has OpenAPI documentation using Swagger. You can also review the developer documentation.

MediaWiki Action API

Що це?

The Wikidata API is MediaWiki's own Action API, extended to include some Wikibase-specific actions: https://wikidata.org/w/api.php

Коли це використовувати?

Використовуйте API, якщо ваша робота включає:

  • Редагування Вікіданих
  • Getting data about entities themselves such as their revision history
  • Getting all of the data of an entity in JSON format, in small groups of entities (up to 50 entities per request).

Don't use the API when your result set is likely to be large. (Consider using a dump in such cases.)

The API is also poorly suited to situations in which you want to request the current state of entities in JSON. (For such cases consider using the Linked Data Interface, which is likelier to provide faster responses.)

Finally, it's probably a bad idea to use the API when you'll need to further narrow the result of your API request. In such cases it's better to frame your work as a search (for Elasticsearch) or a query (for WDQS).

Подробиці

The MediaWiki Action API used for Wikidata is meticulously documented on Wikidata's API page. You can explore and experiment with it using the API Sandbox.

Боти

 
Ми любимо добре вихованих ботів!

Доступ до API можна здійснювати ботом. Детальніше про ботів див. Wikidata:Bots.

Потік останніх змін

Що це?

Потік останніх змін забезпечує безперервний потік змін усіх вікі Вікімедіа, включаючи Вікідані: https://stream.wikimedia.org

Коли це використовувати?

Use the Recent Changes stream when your project requires you to react to changes in real time or when you need all the latest changes coming from Wikidata – for example, when running your own query service.

Подробиці

The Recent Changes stream contains all updates from all wikis using the server-sent events protocol. You'll need to filter Wikidata's updates out on the client side.

You can find the web interface at stream.wikimedia.org and read all about it on the EventStreams page.

Дампи

Що це?

Дампи Вікіданих — це повний експорт усіх сутностей у Вікіданих: https://dumps.wikimedia.org

Коли їх використовувати?

Use a dump when your result set is likely to be very large. You'll also find a dump important when setting up your own query service.

Don't use a dump if you need current data: the dumps take a very long time to export and even longer to sync to your own query service. Dumps are also unsuitable when you have significant limits on your available bandwidth, storage space and/or computing power.

Подробиці

If the records you need to traverse are many, or if your result set is likely to be very large, it's time to consider working with a database dump: (link to the latest complete dump).

You'll find detailed documentation about all Wikimedia dumps on the "Data dumps" page on Meta and about Wikidata dumps in particular on the database download page. See also Flavored dumps above.

Інструменти

  • JsonDumpReader — це бібліотека PHP для читання дампів.
  • На [1] ви знайдете Go-бібліотеку для обробки дампів Вікіпедій та Вікіданих.
  • Ви можете використовувати wdumper, щоб отримати часткові власні дампи RDF.

Служба локальних запитів

It's no small task to procure a Wikidata dump and implement the above tools for working with it, but you can take a further step. If you have the capacity and resources to do so, you can host your own instance of the Wikidata Query Service and query it as much as you like, out of contention with any others.

To set up your own query service, follow these instructions from the query service team, which include procuring your own local copy of the data. You may also find useful information in Adam Shorland's blog post on the topic.