17. JUSTSYSTEMSJUSTSYSTEMS
• select sum(c0) from table;
• select c1, sum(c0) from table group by c1;
• select c1, sum(c0) from table group by c1 where c2 in
('hoge');
17
次のようなSQLの高速化について説明していく
18. JUSTSYSTEMSJUSTSYSTEMS
select sum(c0) from table;
• 取り込みでlongの配列になっている
18
集計関数sum
for (int i = 0; i < c0.lengh; i++) {
sum += c0[i];
}
実はむちゃくちゃ速い!
この性能はそのままは出ない
行数 100万 1000万 1億
long[] 2ms 6ms 57ms
19. JUSTSYSTEMSJUSTSYSTEMS
select sum(c0) from table;
• 繰り上がりを考慮
19
集計関数sum
BigInteger sum = BigInteger.zero;
for (int i = 0; i < c0.lengh; i++) {
sum = sum.add(BigInteger.valueOf(c0[i]));
}
行数 100万 1000万 1億
long[] 2ms 6ms 57ms
BigInteger 37ms 342ms 3470ms
BigIntegerやばい
20. JUSTSYSTEMSJUSTSYSTEMS
select sum(c0) from table;
• 繰り上がりを自前でサポート
20
集計関数sum
for (int i = 0; i < c0.lengh; i++) {
sum += c0[i];
if (sum >= max) {
over++;
sum -= max;
} else if (sum <= -max) {
over--
sum += max;
}
}
(取り込み時に15桁に制限)
25. JUSTSYSTEMSJUSTSYSTEMS
select c1, sum(c0) from table group by c1;
25
グループ化
Map<String, Long> map = new HashMap<>()
for (i = 0; i < c0.length; i++) {
long sum = map.getOrDefault(c1[i], Long.Zero)+c0[i];
map.put(c1[1], sum);
}
27. JUSTSYSTEMSJUSTSYSTEMS
select c1, sum(c0) from table group by c1;
• primitive型を利用したコレクションフレームワークが利
用可能
27
グループ化
Int2LongOpenHashMap map =
new Int2LongOpenHashMap()
for (i = 0; i < c0.length; i++) {
map.addValue(c1[i], c0[i]);
}
28. JUSTSYSTEMSJUSTSYSTEMS
• ID化が威力を発揮するのは複数カラムのグルーピング
select c1.,c2,...,cn, sum(c0) from table group by
c1.,c2,...,cn;
28
グループ化
Object2LongOpenCustomHashMap<String[]> map
= new Object2LongOpenCustomHashMap<>(...);
for (int i = 0; i < c0.length; i++) {
String[] id = new String[n];
for (int j = 1; j <= n; j++) {
id[j] = c[j][i];
}
map.addTo(id, c0[i]);
}
29. JUSTSYSTEMSJUSTSYSTEMS
• ID化により複数カラムを一つのprimitive型に押し込める
select c1.,c2,...,cn, sum(c0) from table group by
c1.,c2,...,cn;
29
グループ化
Int2LongOpenHashMap map
= new Int2LongOpenHashMap<>();
for (int i = 0; i < c0.length; i++) {
int id = 0;
for (int j = 1; j <= n; j++) {
id <<= SHIFT_LENGTH;
id += c[j][i];
}
map.addTo(id, c0[i]);
}
31. JUSTSYSTEMSJUSTSYSTEMS
• String[] を使った絞り込み
select c1, sum(c0) from table group by c1 where
(year,month,day) in (('2018','05','26'),('2018','05','27'));
31
絞り込み
Set<String[]> where = new OpenObjectCustomHashSet<>()
/* where に日付に対応したオブジェクトを入れる */
for (int i = 0; i < c0.length; i++) {
String[] id = new String[n];
for (int j = 1; j <= n; j++) {
id[j] = c[j][i];
}
if (!where.contains(id)) {
continue;
}}
32. JUSTSYSTEMSJUSTSYSTEMS
• ID化により複数カラムを一つのprimitive型に押し込める
select c1, sum(c0) from table group by c1 where
(year,month,day) in (('2018','05','26'),('2018','05','27'));
32
絞り込み
Set<Integer> where = new IntOpenHashSet<>();
/* where に日付に対応したIDを入れる */
for (int i = 0; i < c0.length; i++) {
int id = 0;
for (int j = 1; j <= n; j++) {
id <<= SHIFT_LENGTH;
id += c[j][i];
}
if (!where.contains(id)) {
continue;
}}