Map(key, value)

Map(key, value) data type stores key:value pairs.

Parameters

To get the value from an a Map('key', 'value') column, use a['key'] syntax. This lookup works now with a linear complexity.

Examples

Consider the table:

  1. CREATE TABLE table_map (a Map(String, UInt64)) ENGINE=Memory;
  2. INSERT INTO table_map VALUES ({'key1':1, 'key2':10}), ({'key1':2,'key2':20}), ({'key1':3,'key2':30});

Select all key2 values:

  1. SELECT a['key2'] FROM table_map;

Result:

  1. ┌─arrayElement(a, 'key2')─┐
  2. 10
  3. 20
  4. 30
  5. └─────────────────────────┘

If there’s no such key in the Map() column, the query returns zeros for numerical values, empty strings or empty arrays.

  1. INSERT INTO table_map VALUES ({'key3':100}), ({});
  2. SELECT a['key3'] FROM table_map;

Result:

  1. ┌─arrayElement(a, 'key3')─┐
  2. 100
  3. 0
  4. └─────────────────────────┘
  5. ┌─arrayElement(a, 'key3')─┐
  6. 0
  7. 0
  8. 0
  9. └─────────────────────────┘

Convert Tuple to Map Type

You can cast Tuple() as Map() using CAST function:

  1. SELECT CAST(([1, 2, 3], ['Ready', 'Steady', 'Go']), 'Map(UInt8, String)') AS map;
  1. ┌─map───────────────────────────┐
  2. {1:'Ready',2:'Steady',3:'Go'}
  3. └───────────────────────────────┘

Map.keys and Map.values Subcolumns

To optimize Map column processing, in some cases you can use the keys and values subcolumns instead of reading the whole column.

Example

Query:

  1. CREATE TABLE t_map (`a` Map(String, UInt64)) ENGINE = Memory;
  2. INSERT INTO t_map VALUES (map('key1', 1, 'key2', 2, 'key3', 3));
  3. SELECT a.keys FROM t_map;
  4. SELECT a.values FROM t_map;

Result:

  1. ┌─a.keys─────────────────┐
  2. ['key1','key2','key3']
  3. └────────────────────────┘
  4. ┌─a.values─┐
  5. [1,2,3]
  6. └──────────┘

See Also