Greenplum secrets🎩
699 subscribers
38 photos
8 videos
10 files
67 links
The channel about best practice coding for Greenplum / Канал о том как писать оптимальный код в Greenplum. by @smartyru
Download Telegram
Секрет I (SQL внутри Эксель или Donald Duck возвращается)

За неимением новых секретов от GP буду делиться ништяками из мира OLAP, которые лично мне облегчают жизнь - не сочтите за спам - нумерация оных римскими цифрами.

Давно хотел покрутить мои данные в Excel SQL запросами.
Если ты тоже - есть решение - DuckDB - персистентная колоночная БД с поддержкой NoSQL, которая легко ставится куда угодно, в моем случае на Win 10.
Пишут, что она по архитектуре даже многопоточна, а кто-то уже проверил, что она вычисляет число строк в файле быстрее, чем старый добрый wc -l под X-ами

Первое знакомство с зверушкой - восторг как по функционалу, так и по скорости.

Предположим, у нас есть таблица сделок в XLS-файле, куда мы добавляем новые сделки в крипте.
На уровне XLS отфильтровать сделки по определенному тикеру - нет проблем.
Сложности начинаются, если мы хотим посмотреть доходность незакрытых сделок по определенному тикеру, скажем Nosana ( крипто-токен для оплаты сети AI на базе GPU grid).
Т.к. такие сделки не обязаны быть в соседних строках шита ввиду того, что мы покупаем разные крипто-монеты в разное время, диверсифицируя свой портфель, ф-я SUM в XLS по рэнджу( при выбранном фильтре на тикер) даст неверный рез-т, подхватив промежуточные строки диапазона с другим тикером.

И тут на помощь приходит DuckDB, который по щелчку умеет выгрузить csv ( в который мы сохранили наш XLS ) в табл-у:
create table cdeal as select * from read_csv('C:\tmp\deals.csv', delim=';');

Хотим взглянуть на интересующие нас незакрытке сделки? Пожалуйста(на фото):
select * from cdeal where stock='NOS' and "Sell Date" is null;
Надо подбить прибыли/убытки - легко!
select sum(profit::numeric) from cdeal where stock='NOS' and "Sell Date" is null;

Это был простой пример на 15 мин , который показывает элегантность данного решения
Ваша средняя з.п в уходящем 2024 на руки.Your netto average salary in the outgoing 2024.
Anonymous Poll
10%
< 100 000 RUB
10%
< 150 000
5%
< 200 000
17%
< 250 000
19%
< 300 000
14%
< 350 000
10%
< 400 000
5%
< 450 000
6%
< 500 000
6%
< 550 000
На канале Greenlum Russia сегодня пробежал опрос о зарплатах гринпламовцев.
Т.к. выявлены недовольные разбивкой гистограммы и тут вряд ли есть случайные люди, не связанные с GP,
спешу исправить ситуацию, да что там, мне и самому стало интересно.
Опрос выше и ниже данного дисклэймера
Ваша средняя з.п в уходящем 2024 на руки(продолжение).Your netto average salary in the outgoing 2024( part 2) !
Anonymous Poll
63%
< 600 000 (RUB)
0%
< 650 000
0%
< 700 000
1%
< 750 000
0%
< 800 000
0%
< 850 000
0%
< 900 000
1%
< 950 000
7%
< 1 000 000
28%
Я стейкхолдер компании Arenadata ( I am owner of Arenadata PJSC)
Дорогие друзья! Ввиду того, что пришло время охладиться ( канал уходит в отпуск до 10.01.25), опрос года - рабочий вопрос! __Dear all! Since it's time to cool down (the channel is going on vacation until 10.01.25), the last poll in this year (still regarding business stuff)
Опровержение
Т.к. я обещал завязать с секретами на время отпуска канала, то просто хотел бы поделиться результатами одного эксперимента.
@andreikapolin на канале Greenplum Russia сделал вчера сногсшибательное заявление, цитирую

"Есть партицированная табличка по дате, партиции делаю только с 2022, все что до, в дефолтной
Получается в таблице есть история 3 млрд строк, все лежит в дефолтной
Начинаю подгружать 300 миллионов строк и создавать для них партиции, подвисает, с чем может быть связаны?"

Т.к. меня это заинтриговало, хоть и считаю, что в default партиции не должно быть многолюдно, решил проверить сие утверждение.
Создадим табл-у, куда зальем 3 ярда в дефолтную партицию:
CREATE TABLE tst1
(id INT,
order_date DATE
)
WITH (appendoptimized=true, orientation=column, compresstype=ZLIB, compresslevel=1)
DISTRIBUTED BY(id)
PARTITION BY RANGE(order_date)
(START(date '2022-01-01') INCLUSIVE
END(date '2023-01-01') EXCLUSIVE
EVERY(INTERVAL '1 month'),
DEFAULT PARTITION other);


Синтетика для записи в дефолтную партицию (с пустой датой) :
create table smpl_1m WITH (appendonly = true, orientation = column, compresstype = zstd, compresslevel = 1)
as
select generate_series(1, 1e6::int) id, null::date distributed by(id);

insert into smpl_1m
select s.* from smpl_1m s
join (select generate_series(1,3000)) a
on 1=1

Чек числа строк:
select count(*) from smpl_1m; -- 3 001 000 000

Запишем данные в дефолтную партицию:
insert into tst1
select * from smpl_1m;


Теперь смоделируем шаг записи 300 млн строк в партиции, отличные от дефолта ( которых состоят из 12 месяцев 2022 г. ):
insert into tst1
select id, '2022-01-01'::date + mod(id, 365)
from smpl_1m
limit 300e6::int;

300,000,000 rows affected in 2 m 27 s 313 ms


Теперь создадим таблицу tst2, идентичную tst1 ( скрипт не привожу, чтобы не мусорить - он такой же как для tst1 ) и запишем 300 млн строк
insert into tst2
select id, '2022-01-01'::date + mod(id, 365)
from smpl_1m
limit 300e6::int;

300,000,000 rows affected in 2 m 27 s 203 ms


Вывод: Исходя из имеющихся вводных - вывод автора не подтвержден. Время совпало с точностью до секунды.

Возмоэжно, у @andreikapolin был другой сценарий и если он прочтет этот пост, поделится, в чем разница.
👍2
Полезные заметки о PXF или тонкости интеграции с Hive

Друзья, да здравствет день вечного студента, 25 янааря, а значит пора за уроки!
Вот несколько, которые я извлек при попытке прорубить окно в Hadoop из Greenplum,
тем более, что ответы местами не гуглились, а были обнаружены в нейросетке просветленных коллег.
Зарублю ка на носу тут, на память!

Урок 1.
Так бывает, что в DEV контуре версия либок отстает от прод, и закон Мерфи тут как тут: "Если что-то может пойти не так, оно пойдет не так"!
Обновили как-то в Hadoop сборку, создали с нуля тест табл-у, создали профиль hive в GP, чтобы ее прочитать по PXF.
Создали внешнюю таблицу в GP, запрос к которой рвет с ошибкой
PXF server error : Can not read value at 0 in block -1 in file ...

Вскрытие показало, что в новой конфигурации Hadoop таблица Hive создана в Parquet со сжатием по дефолту zsdt - не поддерживаемый кодек на старой сборке PXF.

Решение:
Указать в DDL Hive в TBLPROPERTIES 'parquet.compression' = 'SNAPPY'

Урок 2.
Создали writable external table в GP, через которую попытались записать 1 млн строк в Hive через jdbc в рамках одной транзакции.
Запрос кончил с ошибкой:
ERROR: PXF server error : Failed to obtain secured JDBC connection
java.sql.SQLTransientConnectionException: HikariPool-74 - Connection is not available, request timed out after 30000ms


Однако, в Hive таблице появилось 130k строк.
Ошибку с ходу не нагуглил, но убедился, что Hive это не про ACID(atomicity, consistency, isolation, durability) и о консистентности транзакций
речи быть не может.

Урок 3.
Не факт, что чтение и запись из/в Hive по PXF через jdbc имеют равные шансы на успех.
Попытался записать данные в Hive через
CREATE WRITaBLE EXTERNAL TABLE ext_hive_jdbc_snappy_w(
"bool" boolean,
"int4" int4,
"int2" int2,
"int_tiny" int2,
"int64_col" int8,
"float_col" float4,
"double_col" float8,
"json_col" text,
"col_binary" bytea,
"timestamp_micros" timestamp)
location ('pxf://...?PROFILE=jdbc&SERVER=...') on all format 'custom' ( formatter='pxfwritable_export' ) encoding 'utf8';

ERROR: PXF server error : Method not supported
Если исключить из insert-а поле с типом bytea, запись выполняется без ошибок.
Да, конечно в Hive через jdbc писать не стоит, для этого есть Spark, но все же неожиданно, на фоне того, что чтение поля binary этой же табл-ы Hive по PXF идет
без проблем, как и должно быть согласно документации (слайд для маппинга под постом )

Решение не найдено.

Урок 4.
Внимательный подписчик заметит, что в маппинге 3 урока нет типа DATE. Спешу вас успокоить, такой необходимый тип таки поддерживается в Hive табл-е,
но в нашей версии PXF сборки 16.1, чтобы прочитать его, также как и timestamp пришлось в DDL внешней табл-ы в GP добавить недокументированную опцию date_wide_range=false,
иначе select полей с этими типами из внешки (PXF external table) стошнит в
ERROR: PXF server error : Illegal conversion
👍51🔥1
Useful notes on PXF or nuances of integration with Hive /*English version of the previous news*/

Friends, long live the day of the eternal student, January 25, which means it's time for lessons!
Here are a few ones that I learned while trying to cut a window into Hadoop from Greenplum,
especially since the answers in some places were not googled, but were found in the neural network of my enlightened colleagues.
I'll write this down for memory!

Lesson 1.
It happens that in the DEV sandbox the version of the binaries lags behind the production, and Murphy's law is right there: "If something can go wrong, it will go wrong"!
We updated the Hadoop assembly somehow, created a test table from scratch, created a hive profile in GP to read it via PXF.
Created an external table in GP, ​​the query to which breaks with the error
PXF server error: Can not read value at 0 in block -1 in file ...

The analysis revealed that in the new Hadoop configuration, the Hive table was created in Parquet with default compression zsdt - an unsupported codec on the old PXF build.

Solution:
Specify in the Hive DDL in TBLPROPERTIES 'parquet.compression' = 'SNAPPY'

Lesson 2.
Created a writable external table in GP, ​​through which they tried to write 1 million rows to Hive via jdbc within a single transaction.
The query ended with an error:
ERROR: PXF server error : Failed to obtain secured JDBC connection
java.sql.SQLTransientConnectionException: HikariPool-74 - Connection is not available, request timed out after 30000ms


However, 130k rows appeared in the Hive table.
I didn't find the error right away, but I was convinced that Hive is not about ACID (atomicity, consistency, isolation, durability) and there can be no talk of transaction consistency.

Lesson 3.
It is not a fact that reading and writing from/to Hive via PXF via jdbc have equal chances of success.
I tried to write data to Hive via
CREATE WRITaBLE EXTERNAL TABLE ext_hive_jdbc_snappy_w(
"bool" boolean,
"int4" int4,
"int2" int2,
"int_tiny" int2,
"int64_col" int8,
"float_col" float4,
"double_col" float8,
"json_col" text,
"col_binary" bytea,
"timestamp_micros" timestamp)
location ('pxf://...?PROFILE=jdbc&SERVER=...') on all format 'custom' ( formatter='pxfwritable_export' ) encoding 'utf8';

and fall in
ERROR: PXF server error : Method not supported
If you exclude the bytea type field from the insert, the write is performed without errors.
Yes, of course, you shouldn't write to Hive via jdbc, there is Spark for that, but still, it's unexpected, given that reading the binary field of the same Hive table via PXF goes
without problems, as it should be according to the documentation (slide for mapping given above the post)

No solution found.

Lesson 4.
An attentive subscriber will notice that there is no DATE type in the mapping of lesson 3. I hasten to reassure you, such a necessary type is supported in the Hive table,
but in our version of PXF build 16.1, to read it, as well as timestamp, we had to add an undocumented option date_wide_range=false to the DDL of the external table in GP,
otherwise, the select of fields with these types from the external table will throw up in
ERROR: PXF server error : Illegal conversion
🔥1
Друзья, не сочтите за спам. Т.к. я уверен в несокрушимом потенциале технологий с открытым исходным кодом, а крипта - яркий пример его реализации на благо цивилизации,
то ее некоторые успехи будут освещаться здесь
Friends, please don't consider this as spam. Since I am confident in the indestructible potential of open source technologies, and crypto is a shining example
of its implementation for the benefit of civilization, some of its successes can be found here
👎21
Секрет 27 ( И снова про перестановку слагаемых или почему 2 <> 1+1 )
Secret 27 (And again about the permutation of terms or why 2 <> 1+1 )
На днях обнаружил рассылку от высокого начальника с вопросом, цитирую
"
Таблица X
Расхождение в объемах более 10 %
ПРОД 897,35 GB
DR 1016,38 GB

Расхождение на момент сверки по количеству строк менее 0,01%
Структура объектов и дистрибьюция совпадают.
Такие ситуации на многих объектах.

Есть объяснение такому расхождению?
"

Я был заинтригован, и проверил все вплоть до типов сжатия полей, т.к. иногда их добавляют без сжатия, полагая, что zstd будет унаследовано от самой таблицы, что не так, как мы знаем из ч.2 секрета 15.
Отличий в этой лист-партицированной AOCO табл-е из 109 млрд строк, разбитой на 6 секций, каждая из 3х bigint и 3х text полей, не нашел, кроме факта озвученного в вопросе - каждая партиция на проде имела недовес ~10% в сравнении с DR

Подумав про VACUUM, который согласно pg_stat_all_tables никогда не делался на обоих контурах, дал рекомендацию сделать оный, который должен вымести потенциальные зомби строки, появившиеся после update/delete, и проверить выровнялся ли размер.

Но вот о чем я не подумал, вернувшись из отпуска, что у нас на DR и PROM число сегментов отличается почти в 3 раза , и это и была истинная причина разницы в объеме.
Secret 27 (And again about the permutation of terms or why 2 <> 1+1 )
The other day I found a mailing from a high-ranking boss with a question, I quote
"
Table X
Volume discrepancy is more than 10%
PROD 897.35 GB
DR 1016.38 GB

Discrepancy at the time of reconciliation by the number of lines is less than 0.01%
Object structure and distribution are the same.
Such situations occur at many objects.

Is there an explanation for this discrepancy?
"

I was intrigued, and checked everything down to the types of field compression, because sometimes they are added without compression,
assuming that zstd will be inherited from the table itself, which is not the case, as we know from part 2 of secret 15.
I did not find any differences in this leaf-partitioned AOCO table of 109 billion rows, divided into 6 sections, each of 3 bigint and 3 text fields, except for the fact voiced in the question - each partition on production had a shortfall of ~10% compared to DR

Having thought about VACUUM, which according to pg_stat_all_tables was never done on both servers, I recommended doing one, which should sweep out potential zombie rows that appeared after update/delete, and check whether the size has aligned.

But what I didn't think about when I returned from vacation is that the number of segments on DR and PROD differs by almost 3 times, and this was the real reason for the difference in volume.

Стало интересно, насколько влияет эта разница.
Создал тривиальный тест из 1 колоночной табл-ы в 1 млн строк.
I became interested in how much this difference affects.
I created a trivial test from a 1-column table with 1 million rows.

create table tst_1m   WITH (appendonly=true,orientation=column,compresstype=zstd,compresslevel=1)
as select generate_series(1,1000000) n distributed by(n);

Размеры табл-иц, на PROD:
Tables size, on PROD:
SQL> select pg_relation_size( 'tst_1m' )
pg_relation_size
-----------------------------------------
3 245 088


на DR:
DR:
SQL> select pg_relation_size( 'tst_1m' )
pg_relation_size
-----------------------------------------
3 166 432


Забавно, что в реальной табл-е картина обратна тесту на синтетике выше, т.е. при увеличении числа сегментов в 3 раза, размер табл-ы на пром уменьшился, но суть, думаю, ясна.
It's funny that in the real table the picture is the opposite of the test on synthetics above, i.e. with a 3-fold increase in the number of segments, the size of the table on the industrial scale decreased, but the essence, I think, is clear.
🤔3🔥1
Срочные новости о нашумевшем ИИ
Не подтверждено, но сообщается, что Wiz Research обнаружили общедоступную базу данных ClickHouse, принадлежащую DeepSeek, где хранится крайне конфиденциальная информация, включая секретные ключи, текстовые сообщения чата, сведения о бэкэнде и журналы.
Breaking news
It is not confirmed, but Wiz Research has reportedly discovered a publicly accessible ClickHouse database owned by DeepSeek that contains highly sensitive information including secret keys, chat text messages, backend details, and logs.
😱3
Пятничный квиз
Friday quizz
Вы создали таблицу X в PostgreSQL, после чего выполнили команду
Что не будет удалено автоматически ?
Варианты ответа ниже
You created a table X in PostgreSQL, then executed the command
What will not be deleted automatically

Answer options below

create table x (
id integer unique default nextval('my_seq') ); --создание таблицы // create table

alter table x drop column id cascade; -- команда // command
Greenplum secrets🎩
Варианты ответа // Answer options
Поздравляю всех, кто ответил "Последовательность"!
Congratulations to all those whose answer was Sequence - that's right!
👍1
В программе обещают про Greenplum, я зарегался
Forwarded from Lyubov Medvedeva
Делюсь конфой, если кому будет интересно) за качество одного доклада точно ручаюсь, будет выступать мой близкий друг)

https://rshb.sk.jugru.org/
🔥5
Секрет 28 ( Massacre или опять BDSM на мелких таблицах )
Secret 28 (Massacre or BDSM on small tables again)
2 дня охотился за запросом : вчера не было данных во временных табл-ах Y и Z,
сегодня повезло - "поймал данные" и зверушку в ловушку.
Вчера и сегодня запрос падал через 1ч20м на проде со спиллом 37 TB
И если вчера в табл-е Y было 22 млн строк, то сегодня 0.
В Z же вчера и сегодня 3 строки DISTRIBUTED RANDOMLY
Таким образом, Обе оказались без собранной статистики ввиду настроек gp_autostats_mode_in_functions = on_change и gp_autostats_on_change_threshold > 1 млн
и опущенного по умолчанию флага принудительного сбора статы внутри CDC ф-ии.
I've been hunting for a query for 2 days: yesterday there was no data in temporary tables Y and Z,
I was lucky today - I "caught the data" and the animal in a trap.
Yesterday and today the query crashed after 1 hour 20 minutes on production with a 37 TB spill
And if yesterday there were 22 million rows in table Y, today there are 0.
In Z, yesterday and today there are 3 rows DISTRIBUTED RANDOMLY
Thus, both ended up without collected statistics due to the settings gp_autostats_mode_in_functions = on_change and gp_autostats_on_change_threshold > 1 million
and the forced stats collection flag inside the CDC function that was omitted by default.

Дичь: Wild beast
select t1.id,
t1.collection_id,
t1.c_group_prop::text,
coalesce(t1.c_date_beg, '1900-01-01'::date) as c_date_beg,
t1.effective_date,
row_number()
over (partition by t1.c_group_prop, t1.collection_id, t1.effective_date order by t1.id desc) as prop_rn
from (select a.*
from rdv.mart_properties a
join (select b.properties_rk, b.effective_date, max(b.version_id) version_id
from rdv.mart_properties b
where (b.version_id between :1 and :2)
group by b.properties_rk, b.effective_date) c
using (properties_rk, effective_date, version_id)
where 1=1
and a.version_id between :1 and :2) t1
inner join Y t2 on t1.collection_id = t2.collection_id
where 1 = 1
and t1.c_group_prop::text in
(select property_id from Z)

Вскрытие показало, что проблема была именно в справочнике с фиксированным наполнением Z, а не в вот этой вот всей сложной аналитике в основной части как подумали 70% из вас ( проваливших прошлый тест -) )
Будь у Z либо корректный хэш (property_id), либо собранная статистика, либо и то и то, то запрос выполнится за секунды,
при том что в <rdv.mart_properties between :1 and :2> 3 млрд строк.
Забавно, что сегодня после inner join в итоге на in фильтр должно было придти 0 строк, но это не спасло.
Так пусть же ваши запросы всегда бьют точно в цель, и на работе, и в жизни.
Не стесняйтесь мелочиться и быть занудой, похоже это и есть путь к успеху.

The investigation found out that the problem was in the reference table with fixed content Z, and not in all this complex analytics in the main part, as 70% of you thought (who failed the last test -) )
If Z had either a correct hash (property_id), or collected statistics, or both, then the query would be executed in seconds,
given that in <rdv.mart_properties between :1 and :2> there are 3 billion rows.
It's funny that today after inner join 0 rows should have come to the in filter, but it didn't save.
So let your queries always hit the mark, both at work and in life.
Don't be shy about being petty and boring, it seems that this is the path to success.
👍3