Checking if key exists in Presto value map
Asked Answered
H

2

19

I am new to Presto, and can't quite figure out how to check if a key is present in a map. When I run a SELECT query, this error message is returned:

Key not present in map: element

SELECT value_map['element'] FROM
mytable
WHERE name = 'foobar'

Adding AND contains(value_map, 'element') does not work

The data type is a string array

SELECT typeof('value_map') FROM mytable 

returns varchar(9)

How would I only select records where 'element' is present in the value_map?

Herstein answered 29/3, 2019 at 22:4 Comment(2)
If the column type is a varchar, then it’s a string, not a map. Can you show some example values for the column?Physic
There is a typographical error -- SELECT typeof(value_map) would show the type of the value_map. SELECT typeof('value_map') shows the type of the 'value_map' string literal.Kathline
K
42

You can lookup a value in a map if the key is present with element_at, like this:

SELECT element_at(value_map, 'element')
FROM ...
WHERE element_at(value_map, 'element') IS NOT NULL
Kathline answered 29/3, 2019 at 22:47 Comment(0)
C
5

element_at is ambiguous in that case -- it'll return NULL when either there's no such key or the key does exist and has NULL associated with it. A guaranteed approach is contains(map_keys(my_map), 'mykey'), which admittedly should be a bit slower than the original variant.

Curium answered 7/2, 2022 at 18:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.