MatrixGate сокращённо называется mxgate — это высокопроизводительный инструмент загрузки данных, поставляемый вместе с MatrixDB.
Производительность загрузки данных с использованием mxgate значительно выше, чем у нативных операторов INSERT. Поскольку mxgate может напрямую взаимодействовать с MXSegment, отсутствует узкое место на уровне мастера (MXMaster).
| Метод записи | Преимущества | Недостатки | Применимые сценарии |
|---|---|---|---|
| Прямой INSERT | Простой интерфейс | Низкая пропускная способность | Низкая пропускная способность, сотни тысяч точек данных/секунду |
| MatrixGate | Высокая пропускная способность Стандартная поддержка реального времени |
Требуется дополнительное развертывание, есть эксплуатационные расходы | Высокая пропускная способность, десятки миллионов точек данных/секунду |
MatrixGate предоставляет следующие режимы работы:
Ниже показано, как использовать эти два режима для загрузки данных в таблицу. Схема таблицы dest следующая:
CREATE TABLE dest(
time timestamp,
c1 int,
c2 text
)DISTRIBUTED BY(c1);
Режим службы предполагает постоянную работу фонового процесса, предоставляющего HTTP-интерфейс для отправки пользователем временных рядов данных. Это наиболее распространённый способ использования в производственных средах.
Для использования режима службы сначала необходимо создать конфигурационный файл, определив параметры подключения к базе данных, целевую таблицу и другие настройки:
mxgate config --db-database test \
--db-master-host localhost \
--db-master-port 5432 \
--db-user mxadmin \
--target public.dest \
--time-format raw \
--delimiter ',' \
> mxgate.conf
Как указано в команде выше:
| Параметр | Описание | Значение |
|---|---|---|
| --db-database | База данных | test |
| --db-master-host | Хост базы данных | localhost |
| --db-master-port | Порт базы данных | 5432 |
| --db-user | Имя пользователя базы данных | mxadmin |
| --target | Целевая таблица | public.dest |
| --time-format | Формат времени | raw (обычный текст) |
| --delimiter | Разделитель | , |
Затем запустите MatrixGate, указав в параметрах запуска созданный конфигурационный файл:
mxgate start --config mxgate.conf
**********************************************************
__ __ _ _ ____ _
| \/ | __ _| |_ _ __(_)_ __/ ___| __ _| |_ ___
| |\/| |/ _` | __| '__| \ \/ / | _ / _` | __/ _ \
| | | | (_| | |_| | | |> <| |_| | (_| | || __/
|_| |_|\__,_|\__|_| |_/_/\_\\____|\__,_|\__\___|
Version: 4.2.0
Your Copy is Licensed to: yMatrix.cn; 2022-03-01; any
**********************************************************
Launching MatrixGate daemon...
MatrixGate daemon started successfully
After the startup is successful, use the curl tool to send HTTP request to submit data.
In production environment, use the HTTP library supported by the programming language to submit data
The test data file rows_header.csv has been prepared, and the content is as follows:
[mxadmin@sdw2 ~]$ cat rows_header.csv
public.dest
2021-01-01 00:00:00,1,a1
2021-01-01 00:00:00,2,a2
2021-01-01 00:00:00,3,a3
When submitting data, the first row must specify the target table name, because the MatrixGate service may have multiple target tables.
Submit data:
curl http://localhost:8086/ -X POST -H 'Content-Type: text/plain' --data-binary "@rows_header.csv"
MatrixGate binds to port 8086 by default, which can be modified through configuration files.
Query the injected data:
test=# select * from dest;
time | c1 | c2
--------------------+-------------------------------------------------------------------------------------------------------------
2021-01-01 00:00:00 | 11 | a11
2021-01-01 00:00:00 | 12 | a12
2021-01-01 00:00:00 | 13 | a13
(3 rows)
For more detailed API parameters, please refer to Document
MatrixGate also provides other operation and maintenance commands for operation and maintenance management.
View Status
mxgate status
**********************************************************
__ __ _ _ ____ _
| \/ | __ _| |_ _ __(_)_ __/ ___| __ _| |_ ___
| |\/| |/ _` | __| '__| \ \/ / | _ / _` | __/ _ \
| | | | (_| | |_| | | |> <| |_| | (_| | || __/
|_| |_|\__,_|\__|_| |_/_/\_\\____|\__,_|\__\___|
Version: 4.2.0
Your Copy is Licensed to: yMatrix.cn; 2022-03-01; any
**********************************************************
PID 15146 alive
Launched At 2021-09-01 14:59:03
Up For 26 seconds
Binary /usr/local/matrixdb-4.2.0.community/bin/mxgated
Log /home/mxadmin/gpAdminLogs/matrixgate.2021-09-01_145904.log
Config /home/mxadmin/mxgate.conf
You can see the service program running status, configuration files and log paths, which are used to track down problems.
Stop service
mxgate stop
**********************************************************
__ __ _ _ ____ _
| \/ | __ _| |_ _ __(_)_ __/ ___| __ _| |_ ___
| |\/| |/ _` | __| '__| \ \/ / | _ / _` | __/ _ \
| | | | (_| | |_| | | |> <| |_| | (_| | || __/
|_| |_|\__,_|\__|_| |_/_/\_\\____|\__,_|\__\___|
Version: 4.2.0
Your Copy is Licensed to: yMatrix.cn; 2022-03-01; any
**********************************************************
PID 15146 stopped
mxgate stop can stop the service.
Command line mode is used to pour data files into one go, and the process exits after the end.
It's still the data file just now. Remove the first row of the target table, only keep the data rows, and execute the following command:
cat rows.csv \| mxgate --source stdin --db-database test --db-master-host localhost --db-master-port 5432 --db-user mxadmin --time-format raw --target public.dest --parallel 2 --delimiter ','
For more methods of file access, please refer to Document
The migration mode is used for high-speed data migration, and supports migration of data tables from other Greenplum5, Greenplum6, and MatrixDB clusters to the current MatrixDB cluster.
The usage is as follows:
mxgate --source transfer \
--src-host 172.31.41.7 \
--src-port 5432 \
--src-db postgres \
--src-user ec2-user \
--src-password abc \
--src-schema public \
--src-table trans_ao \
--compress "gzip" \
--port-base 9129 \
--local-ip 172.31.33.128 \
--db-database ttt \
--target public.trans_ao \
--format text \
--time-format raw \
--use-auto-increment=false
in:
| Parameter name | Description |
|---|---|
| --source | Function portal, 'transfer' must be specified |
| --src-host | IP address of source library master |
| --src-port | Port number of source library master |
| --src-user | Username for connecting to the source library (superuser is recommended) |
| --src-password | Connection Password |
| --src-schema | schema name of the source table |
| --src-table | Table name of the source table |
| --compress | Transfer method from the source database segment host to this data: The blank string "" means non-compression, plain text transmission gzip: Using gzip compression, the linux command gzip that requires the source database must be installed on the segment host lz4: Using lz4 compression, the linux command lz4 that requires the source database must be installed on the segment host recommended lz4 > gzip > non-compression |
| --port-base | A batch of ports will be occupied during transmission, and the port range is 9129~ |
| --local-ip | The IP address that must be connected to the local machine using the source library |
| --db-database | The database name where the migration target table is located |
| --target | The migration target table name can be in the form of \<schema>.\<table>. If the schema name is not written, the default is public |
| --format | text or csv, CSV is required only if there are complex strings (including newlines, quotes, and separators) in the migrated data. When both text/csv are available in other cases, text mode is preferred |
| --time-format | must be raw in transfer mode |
| --use-auto-increment | When the target table includes a self-increment field of serial type, the fields of this type will be skipped by default in mxgate. This option is added to close the logic of skipping mxgate |
Another usage of migration mode is to quickly export data to a file:
mxgate --source transfer \
--src-host 172.31.41.7 \
--src-port 5432 \
--src-db postgres \
--src-user ec2-user \
--src-schema public \
--src-table trans_ao_1 \
--compress "lz4" \
--port-base 9129 \
--local-ip 172.31.33.128 \
--save-to-dir /tmp/receive/ \
--db-database ttt \
--transform nil \
--writer nil \
--target trans_ao
Используйте параметр --save-to-dir, чтобы указать путь к хранилищу файлов.
Обратите внимание, что даже при экспорте в файл необходимо указывать параметры --db-database и --target для определения целевой базы данных и таблицы, которые должны существовать.
Фильтрация миграции может быть задана с помощью SQL через параметр --src-sql, позволяя фильтровать данные, подлежащие синхронизации. Этот параметр применим при миграции из таблицы в таблицу и из таблицы в файл:
mxgate --source transfer \
--src-host 172.31.41.7 \
--src-port 5432 \
--src-db postgres \
--src-user ec2-user \
--src-sql "select * from demo where c1 = 'xxxx'" \
--compress "lz4" \
--port-base 9129 \
--local-ip 172.31.33.128 \
--save-to-dir /tmp/receive/ \
--db-database ttt \
--transform nil \
--writer nil \
--target trans_ao
Более подробную информацию о режиме миграции см. в документации
При работе с временными данными могут возникнуть следующие сценарии:
В версии MatrixGate 4.2 добавлена поддержка семантики UPSERT для решения этих задач.
CREATE TABLE upsert_demo (
ts timestamp
, tagid int
, c1 int
, c2 int
, UNIQUE(ts, tagid)
) DISTRIBUTED BY (tagid);
Обратите внимание: для использования функции UPSERT в базе данных необходимо создать UNIQUE-ограничение на комбинацию device id + timestamp.
upsert_demo1.dat:
2020-11-11|1|10|
upsert_demo2.dat:
2020-11-11|1||20
2020-11-11|2||100
2020-11-11|2|200|
Загрузка upsert_demo1.dat:
cat upsert_demo1.dat|mxgate --source stdin \
--db-database test \
--db-master-host localhost \
--db-master-port 5432 \
--db-user mxadmin \
--time-format raw \
--delimiter "|" \
--target upsert_demo \
--upsert-key ts \
--upsert-key tagid
Результат запроса:
test=# select * from upsert_demo ;
ts | tagid | c1 | c2
--------------------+------+------------------------------------------------------------------------------------------------------
2020-11-11 00:00:00 | 1 | 10 |
(1 row)
Загрузка upsert_demo2.dat:
cat upsert_demo2.dat|mxgate --source stdin \
--db-database test \
--db-master-host localhost \
--db-master-port 5432 \
--db-user mxadmin \
--time-format raw \
--delimiter "|" \
--target upsert_demo \
--upsert-key ts \
--upsert-key tagid
Результат запроса:
test=# select * from upsert_demo ;
ts | tagid | c1 | c2
--------------------+-------------------------------------------------------------------------------------------------------------
2020-11-11 00:00:00 | 1 | 10 | 20
2020-11-11 00:00:00 | 2 | 200 | 100
(2 rows)
Из результатов видно, что строки с одинаковыми значениями ts и tagid были объединены.
mxgate config \
--db-database test \
--db-master-host localhost \
--db-master-port 5432 \
--db-user mxadmin \
--time-format raw \
--delimiter "|" \
--target upsert_demo \
--stream-prepared 0 \
--upsert-key ts \
--upsert-key tagid > mxgate.conf
Примечание: при использовании функции UPSERT в режиме службы необходимо установить параметр stream-prepared в значение 0, иначе может возникнуть взаимоблокировка.
Поскольку MatrixGate внутренне использует механизм внешних таблиц, данные вставляются пакетами (микропакетами) в целевую таблицу. Таким образом, каждая строка данных входит в базу данных одновременно с другими данными в рамках одного пакета. Если формат хотя бы одной строки неверен, весь пакет будет отклонён.
Начиная с версии 4.3, MatrixGate реализовал механизм отказоустойчивости. Одиночная ошибка формата не повлияет на вставку остальных данных, а информация об ошибочной строке будет возвращена и записана в лог.
Примечание: отказоустойчивость работает только для ошибок формата. При нарушении правил ограничений (например, уникального индекса) пакетная запись всё равно завершится сбоем.
В отличие от прежнего поведения, когда при ошибке в данных возвращался HTTP 500, после включения отказоустойчивости код ответа остаётся 200. В теле ответа содержится информация об ошибках, например:
At line: 2
missing data for column "c3"
Конечно, количество допустимых ошибок не бесконечно. Порог отказоустойчивости связан с GUC-параметром: gp_initial_bad_row_limit. Если количество строк с ошибками превышает 5 * gp_initial_bad_row_limit, пакетная запись завершается неудачей.
Более подробную информацию см. в разделе MatrixGate.