在 presto Athena 中包含 String 的函数

contains function for String in presto Athena

我在 Athena 有 table 和 ORC Serde。 table 包含一个名为 greeting_message 的字符串列。它也可以包含 null 值。我想查找 table 中有多少行具有特定文本作为模式。

假设我的示例数据如下所示:

|greeting_message |
|-----------------|
|hello world      |
|What's up        |
|                 |
|hello Sam        |
|                 |
|hello Ram        |
|good morning, hello |
|                 |
|the above row has null |
| Good morning Sir |

现在对于上面的table,如果我们看到总共有10行。其中 7 个没有空值,其中 3 个只有 null/empty 值。

我想知道包含特定单词的行的百分比。

例如,考虑单词 hello。它出现在 4 行中,因此此类行的百分比为 4/10,即 40 %。

另一个例子:单词 morning 出现在 2 条消息中。因此,此类行的百分比为 2/10,即 20%。

注意我也在考虑null分母的计数。

SELECT SUM(greeting_message LIKE '%hello%') / COUNT(*) AS hello_percentage, 
       SUM(greeting_message LIKE '%morning%') / COUNT(*) AS morning_percentage 
FROM tablename

prestoDB(Amazon Athena 引擎)的语法不同于 MySQL。下面的例子是创建一个临时 table WITH greetings AS 然后 SELECT 从那个 table:

WITH greetings AS
  (SELECT 'hello world' as greeting_message UNION ALL
   SELECT 'Whats up' UNION ALL
   SELECT '' UNION ALL
   SELECT 'hello Sam' UNION ALL
   SELECT '' UNION ALL
   SELECT 'hello Ram' UNION ALL
   SELECT 'good morning, hello' UNION ALL
   SELECT '' UNION ALL
   SELECT 'the above row has null' UNION ALL
   SELECT 'Good morning Sir')

 SELECT count_if(regexp_like(greeting_message, '.*hello.*')) / cast(COUNT(1) as real) AS hello_percentage, 
       count_if(regexp_like(greeting_message, '.*morning.*')) / cast(COUNT(1) as real) AS morning_percentage 
FROM greetings

会给出如下结果

hello_percentage morning_percentage
0.4 0.2

regex_like 函数可以支持许多正则表达式选项,包括空格 (\s) 和其他字符串匹配要求。