Data access requests | Tdg
Developer’s guide Data access requests

Data access requests

Глава посвящена запросам данных в TDG. В ней описаны логика и синтаксис запросов, а также представлено несколько сценариев использования.

You will use the already deployed TDG cluster as the environment to run requests.

Preparing a data model

Чтобы загрузить данные в TDG, а затем получать к ним доступ через запросы GraphQL, вам нужно сначала определить модель данных. В нашем примере приводится простая модель с двумя типами объектов: Country (страна) и City (город). В модели представлены следующие поля, индексы и отношения:

../../_images/requests.svg

Чтобы загрузить модель данных в TDG, ее надо представить в виде схемы данных Avro:

[
    {
        "name": "Country",
        "type": "record",
        "fields": [
            {"name": "title", "type": "string"},
            {"name": "phone_code", "type": ["null", "string"]}
        ],
        "indexes": ["title"],
        "relations": [
         { "name": "city", "to": "City", "count": "many", "from_fields": "title", "to_fields": "country" }
        ]
    },
    {
        "name": "City",
        "type": "record",
        "fields": [
            {"name": "title", "type": "string"},
            {"name": "country", "type": "string"},
            {"name": "population", "type": "int"},
            {"name": "capital", "type": "boolean"},
            {"name": "postcodes", "type": {"type":"array", "items":"int"}}
        ],
        "indexes": [
            {"name":"primary", "parts":["title", "country"]},
            "title",
            "country",
            "population",
            "postcodes"
        ]
    }
]

Uploading the data model

Теперь необходимо загрузить модель данных в TDG. Это можно сделать через веб-интерфейс.

  1. Откройте в браузере веб-интерфейс TDG на экземпляре, входящем в набор реплик с кластерной ролью runner. Если вы используете уже развернутый TDG-кластер, URL экземпляра будет следующий: http://172.19.0.2:8082.

  2. On the left menu, click the Model tab.

  3. Paste the data model into the Request field.

    Uploading the data model
  4. Click Submit.

The data model has been uploaded. Now you can insert (upload), select, and delete data.

Uploading data

Загрузить данные в TDG можно с помощью мутации GraphQL:

  1. On the left menu, click the GraphQL tab.

  2. Select default for the desired scheme and clear the request field.

    Вкладка GraphQL
  3. Paste the following request into the left field:

mutation all {
    russia:Country(insert: {
        title: "Russia",
        phone_code: "+7"}) {
    title
    phone_code
    }
    germany:Country(insert: {
        title: "Germany",
        phone_code: "+49"}) {
    title
    }
    moscow:City(insert: {
        title: "Moscow",
        country: "Russia",
        population: 12655050,
        capital: true,
        postcodes: [101000, 119021, 115035, 109028, 109004]}) {
    title
    country
    population
    capital
    postcodes
    }
    spb:City(insert: {
        title: "Saint Petersburg",
        country: "Russia",
        population: 5384342,
        capital: false,
        postcodes: [191193, 191040, 195275, 983002, 983015]}) {
    title
    country
    population
    capital
    postcodes
    }
    tver:City(insert: {
        title: "Tver",
        country: "Russia",
        population: 424969,
        capital: false,
        postcodes: [170006, 170100, 170037, 170028]}) {
    title
    country
    population
    capital
    postcodes
    }
    berlin:City(insert: {
        title: "Berlin",
        country: "Germany",
        population: 3520031,
        capital: true,
        postcodes: [10115, 110117, 10245, 10367]}) {
    title
    country
    population
    capital
    postcodes
    }
    munich:City(insert: {
        title: "Munich",
        country: "Germany",
        population: 1450381,
        capital: false,
        postcodes: [80339, 80336, 80639, 80798]}) {
    title
    country
    population
    capital
    postcodes
    }
    dresden:City(insert: {
        title: "Dresden",
        country: "Germany",
        population: 547172,
        capital: false,
        postcodes: [40210, 40212, 40595, 40627]}) {
    title
    country
    population
    capital
    postcodes
    }
}
  1. Execute the mutation by clicking the Execute Query button:

    Uploading data

The data has been uploaded, as you can see by the system response in the right field.

Data access requests

Here are the common use cases for data access requests:

Примеры запросов GraphQL, приведенные ниже, проще всего запустить через встроенный клиент GraphiQL в веб-интерфейсе TDG. Отправляя запросы на доступ к данным, используйте схему по умолчанию (default):

  1. On the left menu, click the GraphQL tab.

  2. Select default for the desired scheme, clear the request field, and paste the example request code.

General object type query

To select objects of a particular type, specify the type’s name and the object fields to return. You don’t have to indicate all the object fields that are defined in the data model. Specify any number of fields you need. For example:

query {
  Country {
    title
  }
}

Ответ – объект JSON, содержащий массив со всеми записями типа Country. Для каждой записи ответ включает только указанные в запросе поля.

{
  "data": {
    "Country": [
      {
        "title": "Russia"
      },
      {
        "title": "Germany"
      }
    ]
  }
}

Requests by primary index

A specific object can be selected by primary index:

query {
  Country(title: "Germany") {
    title
    phone_code
  }
}

Requests by secondary index

Requests by secondary index have the same syntax:

query {
  City(country: "Russia") {
    title
    country
    population
  }
}

Requests by compound index

To perform a request by compound index, specify an array of field values:

query {
  City(primary: ["Saint Petersburg", "Russia"]) {
    title
    country
    population
  }
}

Запросы по мультиключевому индексу

Мультиключевой индекс (multikey index) – это индекс по полю, которое содержит массив. Если под условие запроса по мультиключевому индексу подходят несколько элементов массива, будет несколько ключей, указывающих на один и тот же объект. Такой объект вернется несколько раз, и это нужно учитывать при составлении запросов и при обработке полученных результатов.

Кроме того, есть ряд ограничений при работе с мультиключевыми индексами:

Note

  • Мультиключевой индекс не может быть первичным.

  • Мультиключевой индекс не может быть составным.

  • Мультиключевой индекс невозможно построить по полю, содержащему сложные типы, например, DateTime, Date, Time и Decimal.

For example:

{
  City(postcodes_gt: 983000) {
    title
    postcodes
  }
}

Запрос вернет объект дважды:

{
  "data": {
    "City": [
      {
        "title": "Saint Petersburg",
        "postcodes": [
          191193,
          191040,
          195275,
          983002,
          983015
        ]
      },
      {
        "title": "Saint Petersburg",
        "postcodes": [
          191193,
          191040,
          195275,
          983002,
          983015
        ]
      }
    ]
  }
}

Comparison operators

Comparison operators are represented by index name suffixes.

Supported operators:

  • _gt (Greater Than)

  • _ge (Greater Than or Equal)

  • _lt (Less Than)

  • _le (Less Than or Equal)

For example:

query {
  City(population_ge: 1000000) {
    title
    country
    population
  }
}

String field indexes support the _like operator so you can search for a particular pattern in a string. You can use the wildcard sign % in the pattern.

query {
  City(title_like: "M%") {
    title
    country
  }
}

Multiple conditions

В одном запросе можно сочетать несколько условий. Тогда TDG будет искать объекты, удовлетворяющие всем условиям одновременно (логическое И). Указывайте в условиях только индексированные поля.

query {
  City(country: "Russia", population_lt: 1000000) {
    title
    country
    population
  }
}

Requests by relations

To select objects by relations, use the same syntax as in the general object type query.

In the example model, there is a one-to-many relationship between the objects Country and City. Consequently, you can get the data both about the country and the cities in one request.

query {
    Country(title: "Russia") {
        title
        city {
            title
            population
    }
    }
}

Response example:

{
  "data": {
    "Country": [
      {
        "title": "Russia",
        "city": [
          {
            "title": "Moscow",
            "population": 12655050
          },
          {
            "title": "Saint Petersburg",
            "population": 5384342
          },
          {
            "title": "Tver",
            "population": 424969
          }
        ]
      }
    ]
  }
}

Pagination

В TDG применяется пагинация на основе курсора. Похожий механизм описан в документации GraphQL.

In general, the request with pagination has the following syntax:

query {
    object_name(first:N, after:$cursor)
    }

where

  • first определяет максимальное количество возвращаемых элементов (по умолчанию 10).

  • after передает непрозрачный курсор – строку, определяющую элемент, с которого система TDG должна продолжить выполнение запроса.

Here is the first request with pagination:

query {
    City(first: 2) {
        title
        country
        cursor
    }
}

The response is the following:

{
  "data": {
    "City": [
      {
        "cursor": "gaRzY2FukqZCZXJsaW6nR2VybWFueQ",
        "country": "Germany",
        "title": "Berlin"
      },
      {
        "cursor": "gaRzY2FukqdEcmVzZGVup0dlcm1hbnk",
        "country": "Germany",
        "title": "Dresden"
      }
    ]
  }
}

To get the next data batch, take the cursor field’s value of the last object received and pass it as the after argument to the next request:

query {
    City(first: 2, after: "gaRzY2FukqdEcmVzZGVup0dlcm1hbnk") {
        title
        country
        cursor
    }
}

Then run this logic in a cycle until you get an empty page:

{
  "data": {
    "City": []
  }
}

Pagination for requests with relations works in a similar way:

query {
  Country(title: "Russia") {
    title
    city(first: 2) {
        title
        population
        cursor
    }
  }
}

Страницы результатов можно выводить и в обратном порядке. В этом случае TDG будет возвращать объекты, предшествующие отмеченному курсором элементу. Чтобы страницы выводились в обратном порядке, укажите для аргумента first отрицательное значение:

query {
    City(first: -2) {
        title
        country
        cursor
    }
}

Requests by version

В TDG реализовано версионирование объектов, поэтому в условие запроса можно включать версии. Подробности вы найдете на этой странице: Версионирование.

Выбор экземпляров для выполнения запросов

В TDG можно определить, на каких узлах будет выполняться запрос.

Поддерживаются следующие параметры:

  • mode – установка целевого экземпляра для выполнения запроса. Тип: string. Значения:

    • write – целевым узлом будет мастер;

    • read – значение по умолчанию.

  • prefer_replica – установка реплики в качестве целевого экземпляра для выполнения запроса. Тип: boolean. Значения:

    • true – предпочитаемой целью будет одна из реплик. Если доступной реплики нет, то запрос будет выполнен на мастере.

    • false (по умолчанию) – запрос будет выполнен на мастер-узле.

    Параметр полезен для ресурсозатратных функций, чтобы избежать снижения скорости работы мастер-узлов;

  • balance – управление балансировкой нагрузки. Тип: boolean. Значения:

    • true (по умолчанию) – запросы будут распределяться по всем экземплярам набора реплик по кругу. При этом, если prefer_replica = true, предпочтение отдается репликам.

    • false – балансировка отключена.

Чтобы установить эти параметры, используйте в запросе GraphQL-директиву @options:

query {
    City @options(mode: read, balance: true) {
        title
        country
        population
    }
}

Эти параметры также можно определить в некоторых функциях программного интерфейса репозитория. Подробности вы найдете на странице Repository API.

Found what you were looking for?
Feedback