IPv4

IPv4是与UInt32类型保持二进制兼容的Domain类型,其用于存储IPv4地址的值。它提供了更为紧凑的二进制存储的同时支持识别可读性更加友好的输入输出格式。

基本使用

  1. CREATE TABLE hits (url String, from IPv4) ENGINE = MergeTree() ORDER BY url;
  2. DESCRIBE TABLE hits;
  1. ┌─name─┬─type───┬─default_type─┬─default_expression─┬─comment─┬─codec_expression─┐
  2. url String
  3. from IPv4
  4. └──────┴────────┴──────────────┴────────────────────┴─────────┴──────────────────┘

同时您也可以使用IPv4类型的列作为主键:

  1. CREATE TABLE hits (url String, from IPv4) ENGINE = MergeTree() ORDER BY from;

在写入与查询时,IPv4类型能够识别可读性更加友好的输入输出格式:

  1. INSERT INTO hits (url, from) VALUES ('https://wikipedia.org', '116.253.40.133')('https://clickhouse.tech', '183.247.232.58')('https://clickhouse.yandex/docs/en/', '116.106.34.242');
  2. SELECT * FROM hits;
  1. ┌─url────────────────────────────────┬───────────from─┐
  2. https://clickhouse.tech/docs/en/ │ 116.106.34.242 │
  3. https://wikipedia.org │ 116.253.40.133 │
  4. https://clickhouse.tech │ 183.247.232.58 │
  5. └────────────────────────────────────┴────────────────┘

同时它提供更为紧凑的二进制存储格式:

  1. SELECT toTypeName(from), hex(from) FROM hits LIMIT 1;
  1. ┌─toTypeName(from)─┬─hex(from)─┐
  2. IPv4 B7F7E83A
  3. └──────────────────┴───────────┘

不可隐式转换为除UInt32以外的其他类型类型。如果要将IPv4类型的值转换成字符串,你可以使用IPv4NumToString()显示的进行转换:

  1. SELECT toTypeName(s), IPv4NumToString(from) as s FROM hits LIMIT 1;
  1. ┌─toTypeName(IPv4NumToString(from))─┬─s──────────────┐
  2. String 183.247.232.58
  3. └───────────────────────────────────┴────────────────┘

或可以使用CAST将它转换为UInt32类型:

  1. SELECT toTypeName(i), CAST(from as UInt32) as i FROM hits LIMIT 1;
  1. ┌─toTypeName(CAST(from, 'UInt32'))─┬──────────i─┐
  2. UInt32 3086477370
  3. └──────────────────────────────────┴────────────┘

来源文章