Would Clickhouse merge cause increase in selected marks? - clickhouse

If clickhouse is performing a background merge operation (lets say 10 parts into 1 part), would that cause the selected marks to go up? Or are selected marks only governed by read operations performed due to SELECT queries

It should not in general but it may because of partition pruning.
create table test( D date, K Int64, S String )
Engine=MergeTree partition by toYYYYMM(D) order by K;
system stop merges test;
insert into test select '2022-01-01', number, '' from numbers(1000000);
insert into test select '2022-01-31', number, '' from numbers(1000000);
select name, min_date, max_date, rows from system.parts where table = 'test' and active;
┌─name─────────┬───min_date─┬───max_date─┬────rows─┐
│ 202201_1_1_0 │ 2022-01-01 │ 2022-01-01 │ 1000000 │ two parts in a partition and min_date
│ 202201_2_2_0 │ 2022-01-31 │ 2022-01-31 │ 1000000 │ min_date & max_date are not intersecting
└──────────────┴────────────┴────────────┴─────────┘
explain estimate select count() from test where D between '2022-01-01' and '2022-01-15';
┌─database─┬─table─┬─parts─┬────rows─┬─marks─┐
│ dw │ test │ 1 │ 1000000 │ 123 │ -- 123 mark.
└──────────┴───────┴───────┴─────────┴───────┘
system start merges test;
optimize table test final;
select name, min_date, max_date, rows from system.parts where table = 'test' and active;
┌─name─────────┬───min_date─┬───max_date─┬────rows─┐
│ 202201_1_2_1 │ 2022-01-01 │ 2022-01-31 │ 2000000 │ one part covers the whole month
└──────────────┴────────────┴────────────┴─────────┘
explain estimate select count() from test where D between '2022-01-01' and '2022-01-15';
┌─database─┬─table─┬─parts─┬────rows─┬─marks─┐
│ dw │ test │ 1 │ 2000000 │ 245 │ -- 245 mark.
└──────────┴───────┴───────┴─────────┴───────┘
In real life you will never notice this because it's very synthetic case, no filters on primary key index, and partition column is not in primary key index.
And it does not mean that merges make query slower, it means that Clickhouse is able to leverage the fact that data is not merged yet and reads only a part of the data in a partition.

Related

Clickhouse bloom filter index seems too slow

I had executed the following query but it has processed ~1B rows and took total time of 75 seconds for a simple count.
SELECT count(*)
FROM events_distributed
WHERE (orgId = '174a4727-1116-4c5c-8234-ab76f2406c4a') AND (timestamp >= '2022-12-05 00:00:00.000000000')
Query id: e4312ff5-6add-4757-8deb-d68e0f3e29d9
┌──count()─┐
│ 13071204 │
└──────────┘
1 row in set. Elapsed: 74.951 sec. Processed 979.00 million rows, 8.26 GB (13.06 million rows/s., 110.16 MB/s.)
I am wondering how I can speed this up? My events table has the following partition by and order by columns and a bloom filter index on orgid
PARTITION BY toDate(timestamp)
ORDER BY (timestamp);
INDEX idx_orgid orgid TYPE bloom_filter(0.01) GRANULARITY 1,
Below is the execution plan
EXPLAIN indexes = 1
SELECT count(*)
FROM events_distributed
WHERE (orgid = '174a4727-1116-4c5c-8234-ab76f240fc4a') AND (timestamp >= '2022-12-05 00:00:00.000000000') AND (timestamp <= '2022-12-06 00:00:00.000000000')
Query id: 879c2ce5-c4c7-4efc-b0e2-25613848afad
┌─explain────────────────────────────────────────────────────────────────────────────────────────────────────┐
│ Expression ((Projection + Before ORDER BY)) │
│ MergingAggregated │
│ Union │
│ Aggregating │
│ Expression (Before GROUP BY) │
│ Filter (WHERE) │
│ ReadFromMergeTree (users.events) │
│ Indexes: │
│ MinMax │
│ Keys: │
│ timestamp │
│ Condition: and((timestamp in (-Inf, '1670284800']), (timestamp in ['1670198400', +Inf))) │
│ Parts: 12/342 │
│ Granules: 42122/407615 │
│ Partition │
│ Keys: │
│ toDate(timestamp) │
│ Condition: and((toDate(timestamp) in (-Inf, 19332]), (toDate(timestamp) in [19331, +Inf))) │
│ Parts: 12/12 │
│ Granules: 42122/42122 │
│ PrimaryKey │
│ Keys: │
│ timestamp │
│ Condition: and((timestamp in (-Inf, '1670284800']), (timestamp in ['1670198400', +Inf))) │
│ Parts: 12/12 │
│ Granules: 30696/42122 │
│ Skip │
│ Name: idx_orgid │
│ Description: bloom_filter GRANULARITY 1 │
│ Parts: 8/12 │
│ Granules: 20556/30696 │
│ ReadFromRemote (Read from remote replica) │
└────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
32 rows in set. Elapsed: 0.129 sec.
How can I speed up this query? because processing 1B rows to give a count of 13M sounds like something is total off. Does creating a SET index on orgid any better? because I will have a max of 10K orgs
The queries I typicall run are
SELECT org_level, min(timestamp) as minTimeStamp,max(timestamp) as maxTimeStamp, toStartOfInterval(toDateTime(timestamp), INTERVAL <step> second) as roundedDownTs, count(*) as cnt, orgid
FROM events_distributed
WHERE orgid = 'foo' and timestamp BETWEEN <one week>
GROUP BY roundedDownTs, orgid, org_level
ORDER BY roundedDownTs DESC;
please note <step> here would be any of the following values 0, 60, 240, 1440, 10080
and another query for a one week time slice but it can be any time slice and always want the results in descending order because of timeseries
SELECT org_text
FROM events_distributed
WHERE (orgid = '174a4727-1116-4c5c-8234-ab76f2406c4a') AND (timestamp >= '2022-12-01 00:00:00.000000000' and timestamp <= '2022-12-07 00:00:00.000000000') order by timestamp DESC LIMIT 51;
You don't use primary index
I suggest is to use
PARTITION BY toDate(timestamp)
ORDER BY (orgId, timestamp)
https://kb.altinity.com/engines/mergetree-table-engine-family/pick-keys/
And remove bloom_filter index.

How to use only the latest state of a particular record in Materialized view?

Let's say I have a table defined as
CREATE TABLE orders (
sqlId Int64, -- orders.id from PSQL
isApproved UInt8, -- Boolean
comment String,
price Decimal(10, 2),
createdAt DateTime64(9, 'UTC'),
updatedAt DateTime64(9, 'UTC') DEFAULT NOW()
)
ENGINE = MergeTree
ORDER BY (createdAt, sqlId)
so two fields that might be changed in the source PSQL database - isApproved and comment
Naturally, if I sink some records from an MQ topic into it, I will end up with something like this
SELECT *
FROM orders
Query id: 50cd95a4-e581-41b5-82a4-7ec86771e4e5
┌─sqlId─┬─isApproved─┬──price─┬─comment───┬─────────────────────createdAt─┬─────────────────────updatedAt─┐
│ 1 │ 1 │ 100.00 │ some note │ 2021-11-08 16:24:07.000000000 │ 2021-11-08 16:27:29.000000000 │
└───────┴────────────┴────────┴───────────┴───────────────────────────────┴───────────────────────────────┘
┌─sqlId─┬─isApproved─┬──price─┬─comment─┬─────────────────────createdAt─┬─────────────────────updatedAt─┐
│ 1 │ 1 │ 100.00 │ │ 2021-11-08 16:24:07.000000000 │ 2021-11-08 16:27:22.000000000 │
└───────┴────────────┴────────┴─────────┴───────────────────────────────┴───────────────────────────────┘
┌─sqlId─┬─isApproved─┬──price─┬─comment─┬─────────────────────createdAt─┬─────────────────────updatedAt─┐
│ 1 │ 0 │ 100.00 │ │ 2021-11-08 16:24:07.000000000 │ 2021-11-08 16:27:17.000000000 │
└───────┴────────────┴────────┴─────────┴───────────────────────────────┴───────────────────────────────┘
In other words, a particular order was created first as a non-approved, then it was approved, then some comment was added.
Let's say I want to create a view that represents the total volume of orders per day.
A naive approach might be:
CREATE MATERIALIZED VIEW orders_volume_per_day (
day DateTime64(9, 'UTC'),
volume SimpleAggregateFunction(sum, Decimal(38, 2))
)
ENGINE = AggregatingMergeTree
PARTITION BY toYYYYMM(day)
ORDER BY day
AS SELECT
toStartOfDay(createdAt) as day,
sum(price) as volume
FROM orders
GROUP BY day
ORDER BY day ASC
However, it will be using all three redundant records, while I only need to use the latest one.
In my particular example, the view will return 300 (3x100) instead of just 100.
Is there any way to achieve the desired behavior in Clickhouse? I know that I can utilize VersionedCollapsingMergeTree somehow with the sign or version columns, but it seems that tools like clickhouse_sinker or snuba will not support it.

Way to achieve overlapping GROUP BY groups with correct subtotals in Clickhouse

Assuming following schema:
CREATE TABLE test
(
date Date,
user_id UInt32,
user_answer UInt8,
user_multi_choice_answer Array(UInt8),
events UInt32
)
ENGINE = MergeTree() ORDER BY date;
And contents:
INSERT INTO test VALUES
('2020-01-01', 1, 5, [2, 3], 15),
('2020-01-01', 2, 6, [1, 2], 7);
Let's say I want to make a query "give me # of users and # of their events grouped by date and user_answer, with subtotals". That's easy:
select date, user_answer, count(distinct user_id), sum(events) from test group by date, user_answer with rollup;
┌───────date─┬─user_answer─┬─uniqExact(user_id)─┬─sum(events)─┐
│ 2020-01-01 │ 5 │ 1 │ 15 │
│ 2020-01-01 │ 6 │ 1 │ 7 │
│ 2020-01-01 │ 0 │ 2 │ 22 │
│ 0000-00-00 │ 0 │ 2 │ 22 │
└────────────┴─────────────┴────────────────────┴─────────────┘
What I can't easily do is making queries with overlapping groups, like when grouping by invidivual options of multiple choice question. For example:
# of users and # of their events grouped by date and user_multi_choice_answer, with subtotals
# of users and # of their events grouped by arbitrary hand-written grouping conditions, like "compare users with user_answer=5 and has(user_multi_choice_answer, 1) to users with has(user_multi_choice_answer, 2)"
For example, with the first query, I would like to see the following:
┌───────date─┬─user_multi_choice_answer─┬─uniqExact(user_id)─┬─sum(events)─┐
│ 2020-01-01 │ 1 │ 1 │ 15 │
│ 2020-01-01 │ 2 │ 2 │ 22 │
│ 2020-01-01 │ 3 │ 1 │ 7 │
│ 2020-01-01 │ 0 │ 2 │ 22 │
│ 0000-00-00 │ 0 │ 2 │ 22 │
└────────────┴──────────────────────────┴────────────────────┴─────────────┘
And for the second:
┌─my_grouping_id─┬─uniqExact(user_id)─┬─sum(events)─┐
│ 1 │ 1 │ 15 │ # users fulfilling arbitrary condition #1
│ 2 │ 2 │ 22 │ # users fulfilling arbitrary condition #2
│ 0 │ 2 │ 22 │ # subtotal
└────────────────┴────────────────────┴─────────────┘
The closest I can get to that is by using arrayJoin():
select date, arrayJoin(user_multi_choice_answer) as multi_answer, count(distinct user_id), sum(events)
from test group by date, multi_answer with rollup;
select arrayJoin(
arrayConcat(
if(user_answer=5 and has(user_multi_choice_answer, 3), [1], []),
if(has(user_multi_choice_answer, 2), [2], [])
)
) as my_grouping_id, count(distinct user_id), sum(events)
from test group by my_grouping_id with rollup;
But that's not a good solution for two reasons:
While it calculates correct results for grouping, the result for sum(events) is not correct for subtotals (as duplicated rows count multiple times)
It doesn't seem efficient, as it makes a lot of data duplication (while I just want the same row to get aggregated into several groups)
So, again, I'm looking for a way that would allow me to easily make grouping of answers to multiple choice questions and gropings by arbitrary conditions on some columns. I'm okay with changing the schema to make that possible, but I'm mostly hoping Clickhouse has a built-in way to achieve that.
While it calculates correct results for grouping, the result for sum(events) is not correct for subtotals (as duplicated rows count multiple times)
You can manually create my_grouping_id = 0 without using rollup. For example,
select arrayJoin(
arrayConcat(
[0],
if(user_answer=5 and has(user_multi_choice_answer, 3), [1], []),
if(has(user_multi_choice_answer, 2), [2], [])
)
) as my_grouping_id, count(distinct user_id), sum(events)
from test group by my_grouping_id
It doesn't seem efficient, as it makes a lot of data duplication (while I just want the same row to get aggregated into several groups)
Currently it's not possible. But I see possibilities. I'll try to make a POC of GROUP BY ARRAY. It seems to be a valid use case.

Clickhouse - join on string columns

I got String column uin in several tables, how do I can effectively join on uin these tables?
In Vertica database we use hash(uin) to transform string column into hash with Int data type - it significantly boosts efficiency in joins - could you recommend something like this? I tried CRC32(s) but it seems to work wrong.
At this moment the CH not very good cope with multi-joins queries (DB star-schema) and the query optimizer not good enough to rely on it completely.
So it needs to explicitly say how to 'execute' a query by using subqueries instead of joins.
Let's emulate your query:
SELECT table_01.number AS r
FROM numbers(87654321) AS table_01
INNER JOIN numbers(7654321) AS table_02 ON (table_01.number = table_02.number)
INNER JOIN numbers(654321) AS table_03 ON (table_02.number = table_03.number)
INNER JOIN numbers(54321) AS table_04 ON (table_03.number = table_04.number)
ORDER BY r DESC
LIMIT 8;
/*
┌─────r─┐
│ 54320 │
│ 54319 │
│ 54318 │
│ 54317 │
│ 54316 │
│ 54315 │
│ 54314 │
│ 54313 │
└───────┘
8 rows in set. Elapsed: 4.244 sec. Processed 96.06 million rows, 768.52 MB (22.64 million rows/s., 181.10 MB/s.)
*/
On my PC it takes ~4 secs. Let's rewrite it using subqueries to significantly speed it up.
SELECT number AS r
FROM numbers(87654321)
WHERE number IN (
SELECT number
FROM numbers(7654321)
WHERE number IN (
SELECT number
FROM numbers(654321)
WHERE number IN (
SELECT number
FROM numbers(54321)
)
)
)
ORDER BY r DESC
LIMIT 8;
/*
┌─────r─┐
│ 54320 │
│ 54319 │
│ 54318 │
│ 54317 │
│ 54316 │
│ 54315 │
│ 54314 │
│ 54313 │
└───────┘
8 rows in set. Elapsed: 0.411 sec. Processed 96.06 million rows, 768.52 MB (233.50 million rows/s., 1.87 GB/s.)
*/
There are other ways to optimize JOIN:
use External dictionary to get rid of join on 'small'-table
use Join table engine
use ANY-strictness
use specific settings like join_algorithm, partial_merge_join_optimizations etc
Some useful refs:
Altinity webinar: Tips and tricks every ClickHouse user should know
Altinity webinar: Secrets of ClickHouse Query Performance
Answer update:
To less storage consumption for String-column consider changing column type to LowCardinality (link 2) that significantly decrease the size of a column with many duplicated elements.
Use this query to get the size of columns:
SELECT
name AS column_name,
formatReadableSize(data_compressed_bytes) AS data_size,
formatReadableSize(marks_bytes) AS index_size,
type,
compression_codec
FROM system.columns
WHERE database = 'db_name' AND table = 'table_name'
ORDER BY data_compressed_bytes DESC
To get a numeric representation of a string need to use one of hash-functions.
SELECT 'jsfhuhsdf', xxHash32('jsfhuhsdf'), cityHash64('jsfhuhsdf');

Faster way for Changing the Array Structure in Clickhouse

I am wondering whether there is a faster way to do what I am trying to do below - basically, unnesting an array and creating a groupArray with different columsn.
-- create table
CREATE TABLE default.t15 ( product String, indx Array(UInt8), col1 String, col2 Array(UInt8)) ENGINE = Memory ;
--insert values
INSERT into t15 values ('p',[1,2,3],'a',[10,20,30]),('p',[1,2,3],'b',[40,50,60]),('p',[1,2,3],'c',[70,80,90]);
-- select values
SELECT * from t15;
┌─product─┬─indx────┬─col1─┬─col2───────┐
│ p │ [1,2,3] │ a │ [10,20,30] │
│ p │ [1,2,3] │ b │ [40,50,60] │
│ p │ [1,2,3] │ c │ [70,80,90] │
└─────────┴─────────┴──────┴────────────┘
DESIRED OUTPUT
┌─product─┬─indx_list─┬─col1_arr──────┬─col2_arr───┐
│ p │ 1 │ ['a','b','c'] │ [10,40,70] │
│ p │ 2 │ ['a','b','c'] │ [20,50,80] │
│ p │ 3 │ ['a','b','c'] │ [30,60,90] │
└─────────┴───────────┴───────────────┴────────────┘
How I am doing it -> [little slow for what I need this for]
SELECT product,
indx_list,
groupArray(col1) col1_arr,
groupArray(col2_list) col2_arr
FROM (
SELECT product,
indx_list,
col1,
col2_list
FROM t15
ARRAY JOIN
indx AS indx_list,
col2 AS col2_list
ORDER BY indx_list,
col1
)x
GROUP BY product,
indx_list;
Basically, I am unnesting the array and then grouping them back.
Is there a better and faster way to do this.
Thanks!
If you want to make it faster it look like you can avoid subselect and the global ORDER BY in it. So something like:
SELECT
product,
indx_list,
groupArray(col1) AS col1_arr,
groupArray(col2_list) AS col2_arr
FROM t15
ARRAY JOIN
indx AS indx_list,
col2 AS col2_list
GROUP BY
product,
indx_list
If you need the arrays to be sorted it's usually better to sort it inside each group separately, using arraySort.
I would make the query a little simple to reduce the count of array joins to one, that probably improves performance:
SELECT
product,
index as indx_list,
groupArray(col1) as col1_arr,
groupArray(element) as col2_arr
FROM
(
SELECT
product,
arrayJoin(indx) AS index,
col1,
col2[index] AS element
FROM default.t15
)
GROUP BY
product,
index;
Maybe make sense to change the table structure to get rid of any arrays. I would suggest the flat schema:
CREATE TABLE default.t15 (
product String,
valueId UInt8, /* indx */
col1 String, /* col1 */
value UInt8) /* col2 */
ENGINE = Memory ;

Resources