Apache Presto 简明教程

Apache Presto - Quick Guide

Apache Presto - Overview

数据分析是对原始数据进行分析以收集相关信息、做出更好决策的过程。它主要用于许多组织中以做出业务决策。大数据分析包含海量数据,且此过程非常复杂,因此公司采用了不同策略。

例如,Facebook 是全球领先的数据驱动和最大的数据仓库公司之一。Facebook 仓库数据存储在 Hadoop 中用于大规模计算。后来,当仓库数据增长到 PB 级别时,他们决定开发一个具有低延迟的新系统。在 2012 年,Facebook 团队成员设计了 “Presto” ,针对交互式查询分析而设计,即使具有 PB 级数据,也能快速运行。

What is Apache Presto?

Apache Presto 是一个分布式并行查询执行引擎,针对低延迟和交互式查询分析而优化。Presto 可以轻松运行查询,并在从 GB 到 PB 的范围内进行扩展,且不会出现宕机。

一个 Presto 查询可以处理来自 HDFS、MySQL、Cassandra、Hive 等多个来源的数据,还可以处理许多其他数据源。Presto 是用 Java 编写的,且易于与其他数据基础设施组件集成。Presto 功能强大,Airbnb、DropBox、Groupon、Netflix 等领先公司都在采用它。

Presto − Features

Presto 包含以下功能:

  1. Simple and extensible architecture.

  2. 可插入连接器 - Presto 支持可插入连接器为查询提供元数据和数据。

  3. 管道式执行 - 避免不必要的 I/O 延迟开销。

  4. 用户自定义函数 - 分析师可以创建自定义用户自定义函数来轻松迁移。

  5. Vectorized columnar processing.

Presto − Benefits

以下是 Apache Presto 提供的好处:

  1. Specialized SQL operations

  2. 易于安装和调试

  3. Simple storage abstraction

  4. 低延迟下快速扩展 PB 级数据

Presto − Applications

Presto 支持当今大多数最佳行业应用。让我们来看一下一些著名应用。

  1. Facebook - Facebook 针对数据分析需求构建了 Presto。Presto 可以轻松扩展大量数据。

  2. Teradata - Teradata 在大数据分析和数据仓库中提供端到端解决方案。Teradata 为 Presto 做出的贡献使更多公司能够满足所有分析需求。

  3. Airbnb - Presto 是 Airbnb 数据基础设施中不可或缺的一部分。实际上,每天有数百名员工使用该技术运行查询。

Why Presto?

Presto 支持标准 ANSI SQL,这让数据分析师和开发人员的工作变得非常轻松。尽管它以 Java 编写,但它避免了 Java 代码与内存分配和垃圾回收相关的典型问题。Presto 具有与 Hadoop 友好的连接器架构。它允许轻松插入文件系统。

Presto 在多个 Hadoop 分布上运行。此外,Presto 可以通过一个 Hadoop 平台查询 Cassandra、关系型数据库或其他数据存储。这种跨平台分析功能允许 Presto 用户从千兆字节到拍字节的数据中提取最大业务价值。

Apache Presto - Architecture

Presto 的架构几乎类似于经典 MPP(海量并行处理)DBMS 架构。下图说明了 Presto 的架构。

presto architecture

上述图表包含不同的组件。下表详细描述了每个组件。

S.No

Component & Description

1.

Client 客户端(Presto CLI)向协调器提交 SQL 语句以获得结果。

2.

Coordinator 协调器是一个主守护进程。协调器最初解析 SQL 查询,然后分析并计划查询执行。调度程序执行管道执行,将工作分配给最接近的节点并监控进度。

3.

Connector 存储插件被称为连接器。Hive、HBase、MySQL、Cassandra 及其他许多都充当连接器;否则你也可以实现一个自定义连接器。连接器为查询提供元数据和数据。协调器使用连接器获取元数据来构建查询计划。

4.

Worker 协调器将任务分配给工作节点。这些工作节点从连接器获取实际数据。最后,工作节点将结果传递给客户端。

Presto − Workflow

Presto 是一个分布式系统,在集群的节点上运行。Presto 的分布式查询引擎经过优化,适用于交互分析,并支持标准 ANSI SQL,包括复杂查询、聚合、连接和窗口函数。Presto 架构简单而可扩展。Presto 客户端(CLI)向一个主守护进程协调器提交 SQL 语句。

调度器通过执行管道连接。调度器会将工作分配给最靠近数据且可以监控进度的节点。协调器将任务分配给多个工作节点,最终工作节点将结果返回给客户端。客户端从输出进程获取数据。可扩展性是一项主要的设计要点。像 Hive、HBase、MySQL 等可插入连接器可为查询提供元数据和数据。Presto 采用“简单存储抽象”进行设计,使针对不同类型数据源提供 SQL 查询功能变得容易。

Execution Model

Presto 利用专为支持 SQL 语义而设计的操作员,支持自定义查询和执行引擎。除了改进调度外,所有处理工作都在内存中执行,并在不同阶段通过网络进行管道传输。这避免了不必要的 I/O 延迟开销。

Apache Presto - Installation

本章将解释如何在您的机器上安装 Presto。让我们了解 Presto 的基本要求,

  1. Linux or Mac OS

  2. Java version 8

现在,让我们继续执行以下步骤在您的机器上安装 Presto。

Verifying Java installation

希望您现在已在您的机器上安装了 Java 8,您只需使用以下命令对其进行验证。

$ java -version

如果 Java 已成功安装在您的机器上,您将看到已安装的 Java 版本。如果未安装 Java,请按照后续步骤在您的机器上安装 Java 8。

下载 JDK。访问以下链接下载最新版本的 JDK。

最新版本是 JDK 8u 92,文件为 “jdk-8u92-linux-x64.tar.gz”。请在您的机器上下载该文件。

然后,解压文件并移动到指定目录。

然后设置 Java 替代项。最终,Java 将安装在您的机器上。

Apache Presto Installation

访问以下链接下载最新版本的 Presto,

现在,“presto-server-0.149.tar.gz” 的最新版本将下载到您的机器上。

Extract tar Files

使用以下命令解压 tar 文件 −

$ tar  -zxf  presto-server-0.149.tar.gz
$ cd presto-server-0.149

Configuration Settings

Create “data” directory

在安装目录之外创建一个数据目录,该目录将用于存储日志、元数据等,以便在升级 Presto 时可以轻松保存。可使用以下代码定义该目录 −

$ cd
$ mkdir data

要查看它的位置路径,请使用命令“pwd”。此位置将在次の节点配置文件中分配。

Create “etc” directory

使用以下代码在 Presto 安装目录内创建一个等目录 −

$ cd presto-server-0.149
$ mkdir etc

该目录将保存配置文件。让我们逐个创建每个文件。

Node Properties

Presto 节点配置文件包含特定于每个节点的环境配置。使用以下代码在等目录 (etc/node.properties) 中创建该文件 −

$ cd etc
$ vi node.properties

node.environment = production
node.id = ffffffff-ffff-ffff-ffff-ffffffffffff
node.data-dir = /Users/../workspace/Presto

完成所有更改后,保存文件并退出终端。其中 node.data 是上述创建的 data 目录的位置路径。 node.id 表示每个节点的唯一标识符。

JVM Config

在 etc 目录中创建一个文件 “jvm.config”(etc/jvm.config)。此文件包含用于启动 Java 虚拟机的命令行选项列表。

$ cd etc
$ vi jvm.config

-server
-Xmx16G
-XX:+UseG1GC
-XX:G1HeapRegionSize = 32M
-XX:+UseGCOverheadLimit
-XX:+ExplicitGCInvokesConcurrent
-XX:+HeapDumpOnOutOfMemoryError
-XX:OnOutOfMemoryError = kill -9 %p

完成所有更改后,保存文件并退出终端。

Config Properties

在 etc 目录中创建一个文件 “config.properties”(etc/config.properties)。此文件包含 Presto 服务器的配置。如果设置一台机器用于测试,Presto 服务器只能充当使用以下代码定义的协调进程 −

$ cd etc
$ vi config.properties

coordinator = true
node-scheduler.include-coordinator = true
http-server.http.port = 8080
query.max-memory = 5GB
query.max-memory-per-node = 1GB
discovery-server.enabled = true
discovery.uri = http://localhost:8080

在此,

  1. coordinator − master node.

  2. node-scheduler.include-coordinator − 允许在协调器上计划任务。

  3. http-server.http.port − 指定 HTTP 服务器的端口。

  4. query.max-memory=5GB − 分布式内存的最大值。

  5. query.max-memory-per-node=1GB − 每个节点的最大内存值。

  6. discovery-server.enabled − Presto 使用 Discovery 服务查找群集中的所有节点。

  7. discovery.uri − Discovery 服务器的 URI。

如果设置多台机器 Presto 服务器,Presto 将充当协调进程和工作进程。使用此配置设置在多台机器上测试 Presto 服务器。

Configuration for Coordinator

$ cd etc
$ vi config.properties

coordinator = true
node-scheduler.include-coordinator = false
http-server.http.port = 8080
query.max-memory = 50GB
query.max-memory-per-node = 1GB
discovery-server.enabled = true
discovery.uri = http://localhost:8080

Configuration for Worker

$ cd etc
$ vi config.properties

coordinator = false
http-server.http.port = 8080
query.max-memory = 50GB
query.max-memory-per-node = 1GB
discovery.uri = http://localhost:8080

Log Properties

在 etc 目录中创建一个文件 “log.properties”(etc/log.properties)。此文件包含命名日志记录程序层次结构的最低日志级别。它使用以下代码定义 −

$ cd etc
$ vi log.properties
com.facebook.presto = INFO

保存文件并退出终端。在此,使用了 DEBUG、INFO、WARN 和 ERROR 四个日志级别。默认日志级别为 INFO。

Catalog Properties

在 etc 目录中创建一个目录 “catalog”(etc/catalog)。这将用于装载数据。例如,使用以下内容创建 etc/catalog/jmx.properties ,以将 jmx connector 装载为 jmx 目录 −

$ cd etc
$ mkdir catalog
$ cd catalog
$ vi jmx.properties
connector.name = jmx

Start Presto

可以使用以下命令启动 Presto,

$ bin/launcher start

然后,您将看到类似于此的响应,

Started as 840

Run Presto

若要启动 Presto 服务器,请使用以下命令 −

$ bin/launcher run

在成功启动 Presto 服务器后,您可在 “var/log” 目录中找到日志文件。

  1. launcher.log − 这是由启动器创建的日志并连接到服务器的 stdout 和 stderr 流。

  2. server.log − 这是 Presto 使用的主要日志文件。

  3. http-request.log − HTTP 请求由服务器收到。

到目前为止,您已在自己的计算机上成功安装了 Presto 配置设置。让我们继续执行步骤来安装 Presto CLI。

Install Presto CLI

Presto CLI 提供了基于终端的交互式 shell,用于运行查询。

通过访问以下链接下载 Presto CLI,

现在,您的计算机上将安装“presto-cli-0.149-executable.jar”。

Run CLI

在下载 presto-cli 后,将其复制到要从中运行它的位置。此位置可以是具有到协调器网络访问权限的任何节点。首先将 Jar 文件的名称更改为 Presto。然后使用以下代码通过 chmod + x 命令使其可执行 −

$ mv presto-cli-0.149-executable.jar presto
$ chmod +x presto

现在使用以下命令执行 CLI,

./presto --server localhost:8080 --catalog jmx --schema default
Here jmx(Java Management Extension) refers to catalog and default referes to schema.

您将看到以下响应,

 presto:default>

现在,在您的终端上键入“jps”命令,您将看到正在运行的守护程序。

Stop Presto

在执行所有执行操作后,可以使用以下命令停止 presto 服务器 −

$ bin/launcher stop

Apache Presto - Configuration Settings

本章将讨论 Presto 的配置设置。

Presto Verifier

Presto Verifier 可用于将 Presto 与另一个数据库(如 MySQL)进行测试,或将两个 Presto 集群彼此进行测试。

Create Database in MySQL

打开 MySQL 服务器并使用以下命令创建一个数据库。

create database test

现在你在服务器中创建了“test”数据库。创建表并使用以下查询加载它。

CREATE TABLE verifier_queries(
   id INT NOT NULL AUTO_INCREMENT,
   suite VARCHAR(256) NOT NULL,
   name VARCHAR(256),
   test_catalog VARCHAR(256) NOT NULL,
   test_schema VARCHAR(256) NOT NULL,
   test_prequeries TEXT,
   test_query TEXT NOT NULL,
   test_postqueries TEXT,
   test_username VARCHAR(256) NOT NULL default 'verifier-test',
   test_password VARCHAR(256),
   control_catalog VARCHAR(256) NOT NULL,
   control_schema VARCHAR(256) NOT NULL,
   control_prequeries TEXT,
   control_query TEXT NOT NULL,
   control_postqueries TEXT,
   control_username VARCHAR(256) NOT NULL default 'verifier-test',
   control_password VARCHAR(256),
   session_properties_json TEXT,
   PRIMARY KEY (id)
);

Add Config Settings

创建一个属性文件以配置验证器-

$ vi config.properties

suite = mysuite
query-database = jdbc:mysql://localhost:3306/tutorials?user=root&password=pwd
control.gateway = jdbc:presto://localhost:8080
test.gateway = jdbc:presto://localhost:8080
thread-count = 1

这里,在 query-database 字段中,输入以下内容:mysql 数据库名称、用户名和密码。

Download JAR File

通过访问以下链接下载 Presto 验证器 jar 文件,

现在已在你的机器上下载版本 “presto-verifier-0.149-executable.jar”

Execute JAR

使用以下命令执行 JAR 文件,

$ mv presto-verifier-0.149-executable.jar verifier
$ chmod+x verifier

Run Verifier

使用以下命令运行验证器,

$ ./verifier config.properties

Create Table

我们使用以下查询在 “test” 数据库中创建一个简单表。

create table product(id int not null, name varchar(50))

Insert Table

创建表后,使用以下查询插入两条记录,

insert into product values(1,’Phone')
insert into product values(2,’Television’)

Run Verifier Query

在验证器终端(./verifier config.propeties)中执行以下示例查询,以检查验证器结果。

Sample Query

insert into verifier_queries (suite, test_catalog, test_schema, test_query,
control_catalog, control_schema, control_query) values
('mysuite', 'mysql', 'default', 'select * from mysql.test.product',
'mysql', 'default', 'select * from mysql.test.product');

这里, select * from mysql.test.product 查询引用 mysql 目录, test 是数据库名称, product 是表名称。通过这种方式,你可以使用 Presto 服务器访问 mysql 连接器。

这里,两个相同的 select 查询彼此进行测试,以查看性能。类似地,你可以运行其他查询来测试性能结果。你还可以连接两个 Presto 集群来检查性能结果。

Apache Presto - Administration Tools

在本章中,我们将讨论 Presto 中使用的管理工具。让我们从 Presto 的 Web 界面开始。

Web Interface

Presto 提供了一个用于监控和管理查询的 Web 界面。可以从协调器 Config 属性中指定的端口号访问它。

启动 Presto 服务器和 Presto CLI。然后,您可以从以下 url 访问 Web 界面 − http://localhost:8080/

web interface

输出将与上述屏幕相似。

在此,主页具有查询列表以及以下信息:唯一查询 ID、查询文本、查询状态、完成百分比、用户名和此查询的来源。最新的查询首先运行,然后在底部显示已完成或未完成的查询。

Tuning the Performance on Presto

如果 Presto 集群有任何与性能相关的问题,请将您的默认配置设置更改为以下设置。

Config Properties

  1. task. info -refresh-max-wait − 减少协调器工作量。

  2. task.max-worker-threads − 分割进程并分配给每个工作程序节点。

  3. distributed-joins-enabled − 哈希-based 分布式联接。

  4. node-scheduler.network-topology − 设置网络拓扑到调度器。

JVM Settings

将默认 JVM 设置更改为以下设置。这有助于诊断垃圾回收问题。

-XX:+PrintGCApplicationConcurrentTime
-XX:+PrintGCApplicationStoppedTime
-XX:+PrintGCCause
-XX:+PrintGCDateStamps
-XX:+PrintGCTimeStamps
-XX:+PrintGCDetails
-XX:+PrintReferenceGC
-XX:+PrintClassHistogramAfterFullGC
-XX:+PrintClassHistogramBeforeFullGC
-XX:PrintFLSStatistics = 2
-XX:+PrintAdaptiveSizePolicy
-XX:+PrintSafepointStatistics
-XX:PrintSafepointStatisticsCount = 1

Apache Presto - Basic SQL Operations

在本章中,我们将讨论如何在 Presto 上创建并执行查询。我们来了解一下 Presto 支持的基本数据类型。

Basic Data Types

下表描述了 Presto 的基本数据类型。

S.No

Data type & Description

1.

VARCHAR Variable length character data

2.

BIGINT A 64-bit signed integer

3.

DOUBLE 64 位浮点双精度值

4.

DECIMAL 一个固定精度的小数。例如 DECIMAL(10,3) - 10 是精度,即数字的总数,3 是表示小数点的小数位。小数位是可选的,默认值为 0

5.

BOOLEAN 布尔值 true 和 false

6.

VARBINARY Variable length binary data

7.

JSON JSON data

8.

DATE 表示为年-月-日的日期数据类型

9.

TIME, TIMESTAMP, TIMESTAMP with TIME ZONE TIME - Time of the day (hour-min-sec-millisecond) TIMESTAMP - Date and time of the day TIMESTAMP with TIME ZONE - Date and time of the day with time zone from the value

10.

INTERVAL Stretch or extend date and time data types

11.

ARRAY Array of the given component type. For example, ARRAY[5,7]

12.

MAP Map between the given component types. For example, MAP(ARRAY[‘one’,’two’],ARRAY[5,7])

13.

ROW Row structure made up of named fields

Presto − Operators

Presto operators are listed in the following table.

S.No

Operator & Description

1.

Arithmetic operatorPresto supports arithmetic operators such as +, -, *, /, %

2.

Relational operator<,>,⇐,>=,=,<>

3.

Logical operatorAND, OR, NOT

4.

Range operatorRange operator is used to test the value in a specific range. Presto supports BETWEEN, IS NULL, IS NOT NULL, GREATEST and LEAST

5.

Decimal operatorBinary arithmetic decimal operator performs binary arithmetic operation for decimal type Unary decimal operator − The - operator performs negation

6.

String operatorThe *‘

’ operator* performs string concatenation

7.

Date and time operatorPerforms arithmetic addition and subtraction operations on date and time data types

8.

Array operatorSubscript operator[] - access an element of an array Concatenation operator

- concatenate an array with an array or an element of the same type

9.

Map operatorMap subscript operator [] - retrieve the value corresponding to a given key from a map

Apache Presto - SQL Functions

到目前为止,我们在讨论对 Presto 运行一些基本查询。本章将讨论重要的 SQL 函数。

Math Functions

数学函数处理数学公式。下表详细描述了函数列表。

S.No.

Function & Description

1.

abs(x) 返回 x 的绝对值

2.

cbrt(x) 返回 x 的立方根

3.

ceiling(x) 返回 x 值四舍五入到最接近的整数

4.

ceil(x) Alias for ceiling(x)

5.

degrees(x) 返回 x 的度值

6.

e(x) 返回欧拉数的双值

7.

exp(x) 返回欧拉数的指数值

8.

floor(x) 返回 x 四舍五入到最接近的整数

9.

from_base(string,radix) 返回解释为基数数字的字符串的值

10.

ln(x) 返回 x 的自然对数

11.

log2(x) 返回 x 的以 2 为基的对数

12.

log10(x) 返回 x 的以 10 为基的对数

13.

log(x,y) 返回 y 为基, x 为值的以 y 为基的对数

14.

mod(n,m) 返回 n 除以 m 的模数(余数)

15.

pi() 返回圆周率值。结果将作为双精度浮点数值返回

16.

power(x,p) 返回值 ‘p’x 次方

17.

pow(x,p) Alias for power(x,p)

18.

radians(x) 将角度 x 转换为弧度

19.

rand() Alias for radians()

20.

random()Returns the pseudo-random value

21.

rand(n) Alias for random()

22.

round(x) 返回x的四舍五入值

23.

round(x,d)x 值四舍五入为 ‘d’ 位小数

24.

sign(x) 返回值x的正负号函数,即,当参数为0时返回0,当参数大于0时返回1,当参数小于0时返回-1。对于双精度参数,该函数会另外返回NaN,如果参数为NaN,返回1,如果参数为+Infinity,返回-1,如果参数为-Infinity

25.

sqrt(x) 返回 x 的平方根

26.

to_base(x,radix) 返回值类型为archer。结果作为 x 的基数返回

27.

truncate(x) 截断 x 的值

28.

width_bucket(x, bound1, bound2, n) 返回 x 的bin数,指定的界限1和界限2的界限以及n个桶数

29.

width_bucket(x, bins) 根据数组bins指定的bins返回 x 的bin数

Trigonometric Functions

三角函数参数表示为弧度()。下表列出了这些函数。

S.No

Functions & Description

1.

acos(x) 返回反余弦值(x)

2.

asin(x) 返回反正弦值(x)

3.

atan(x) 返回反正切值(x)

4.

atan2(y,x) 返回反正切值(y/x)

5.

cos(x) Returns the cosine value(x)

6.

cosh(x) 返回双曲余弦值(x)

7.

sin(x)Returns the sine value(x)

8.

tan(x) Returns the tangent value(x)

9.

tanh(x) 返回双曲正切值(x)

Bitwise Functions

下表列出了按位函数。

S.No

Functions & Description

1.

bit_count(x, bits) 计算位数

2.

bitwise_and(x,y) 对两个位执行按位 AND 运算, xy

3.

bitwise_or(x,y) 两个位 x, y 之间的按位 OR 运算

4.

bitwise_not(x) 对位 x 执行按位 NOT 运算

5.

bitwise_xor(x,y) 对位 x, y 执行 XOR 运算

String Functions

下表列出了字符串函数。

S.No

Functions & Description

1.

concat(string1, …​, stringN) 连接给定的字符串

2.

length(string) 返回给定字符串的长度

3.

lower(string) 返回字符串的小写格式

4.

upper(string) 返回给定字符串的大写格式

5.

lpad(string, size, padstring) 对给定字符串进行左填充

6.

ltrim(string) 移除字符串中的前导空白

7.

replace(string, search, replace) 替换字符串值

8.

reverse(string) 反转对字符串执行的操作

9.

rpad(string, size, padstring) 对给定的字符串进行右填充

10.

rtrim(string) 移除字符串中的结尾空白

11.

split(string, delimiter) 在分隔符处拆分字符串,并返回一个大小不超过限制的数组

12.

split_part(string, delimiter, index) 在分隔符处拆分字符串并返回字段索引

13.

strpos(string, substring) 返回子字符串在字符串中的起始位置

14.

substr(string, start) 返回给定字符串的子字符串

15.

substr(string, start, length) 返回具有指定长度的给定字符串的子字符串

16.

trim(string) 删除字符串中的前导和尾随空白

Date and Time Functions

下表列出了日期和时间函数。

S.No

Functions & Description

1.

current_dateReturns the current date

2.

current_timeReturns the current time

3.

current_timestampReturns the current timestamp

4.

current_timezone()Returns the current timezone

5.

now() 返回当前日期和具有时区的timestamp

6.

localtimeReturns the local time

7.

localtimestampReturns the local timestamp

Regular Expression Functions

下表列出了正则表达式函数。

S.No

Functions & Description

1.

regexp_extract_all(string, pattern) 返回与模式的正则表达式相匹配的字符串

2.

regexp_extract_all(string, pattern, group) 返回与模式和组的正则表达式相匹配的字符串

3.

regexp_extract(string, pattern) 返回与模式的正则表达式相匹配的第一个子字符串

4.

regexp_extract(string, pattern, group) 返回与模式和组的正则表达式相匹配的第一个子字符串

5.

regexp_like(string, pattern) 返回与模式匹配的字符串。如果返回字符串,则该值为 true,否则为 false

6.

regexp_replace(string, pattern) 使用模式替换与表达式匹配的字符串的实例

7.

regexp_replace(string, pattern, replacement) 使用模式和替换替换与表达式匹配的字符串的实例

8.

regexp_split(string, pattern) 拆分给定模式的正则表达式

JSON Functions

下表列出了 JSON 函数。

S.No

Functions & Description

1.

json_array_contains(json, value) 检查值是否存在于 json 数组中。如果值存在,则返回 true,否则返回 false

2.

json_array_get(json_array, index) 获取 json 数组中索引的元素

3.

json_array_length(json) 返回 json 数组的长度

4.

json_format(json) 返回 json 结构格式

5.

json_parse(string) 将字符串解析为 json

6.

json_size(json, json_path) 返回 value 的大小

URL Functions

下表列出了 URL 函数。

S.No

Functions & Description

1.

url_extract_host(url)Returns the URL’s host

2.

url_extract_path(url)Returns the URL’s path

3.

url_extract_port(url)Returns the URL’s port

4.

url_extract_protocol(url)Returns the URL’s protocol

5.

url_extract_query(url) 返回 URL 的查询字符串

Aggregate Functions

下表列出了汇总函数。

S.No

Functions & Description

1.

avg(x) 返回给定值的平均值

2.

min(x,n) 从两个值中返回最小值

3.

max(x,n) 从两个值中返回最大值

4.

sum(x) 返回 value 的和

5.

count(*) 返回输入行数

6.

count(x) 返回输入值的计数

7.

checksum(x) 返回 x 的校验和

8.

arbitrary(x) 返回 x 的任意值

Color Functions

下表列出了颜色函数。

S.No

Functions & Description

1.

bar(x, width) 使用 rgb low_color 和 high_color 渲染一个条

2.

bar(x, width, low_color, high_color) 为指定宽度渲染一个条

3.

color(string) 返回输入字符串的颜色值

4.

render(x, color) 使用 ANSI 颜色代码使用特定颜色渲染值 x

5.

render(b) 接受布尔值 b,并使用 ANSI 颜色代码渲染一个绿色的 true 或一个红色的 false

6.

rgb(red, green, blue) 通过 int 参数作为颜色的 RGB 分量的三个值返回一个颜色值,该颜色值的范围为 0 到 255

Array Functions

下表列出了数组函数。

S.No

Functions & Description

1.

array_max(x) 在数组中找到最大元素

2.

array_min(x) 在数组中找到最小元素

3.

array_sort(x) 对数组中的元素进行排序

4.

array_remove(x,element) 从数组中移除特定元素

5.

concat(x,y)Concatenates two arrays

6.

contains(x,element) 在数组中查找给定元素。如果存在,则返回 true;否则,返回 false

7.

array_position(x,element) 在数组中找到给定元素的位置

8.

array_intersect(x,y) 执行两个数组之间的交集

9.

element_at(array,index) 返回数组元素位置

10.

slice(x,start,length) 按特定长度切片数组元素

Teradata Functions

下表列出了 Teradata 函数。

S.No

Functions & Description

1.

index(string,substring) 返回子字符串的字符串索引

2.

substring(string,start) 返回给定字符串的子字符串。可以指定开始索引

3.

substring(string,start,length) 为给定字符串的特定开始索引和长度返回子字符串

Apache Presto - MySQL Connector

The MySQL connector is used to query an external MySQL database.

Prerequisites

MySQL server installation.

Configuration Settings

Hopefully you have installed mysql server on your machine. To enable mysql properties on Presto server, you must create a file “mysql.properties” in “etc/catalog” directory. Issue the following command to create a mysql.properties file.

$ cd etc
$ cd catalog
$ vi mysql.properties

connector.name = mysql
connection-url = jdbc:mysql://localhost:3306
connection-user = root
connection-password = pwd

Save the file and quit the terminal. In the above file, you must enter your mysql password in connection-password field.

Create Database in MySQL Server

打开 MySQL 服务器并使用以下命令创建一个数据库。

create database tutorials

Now you have created “tutorials” database in the server. To enable database type, use the command “use tutorials” in the query window.

Create Table

我们来在“tutorials”数据库中创建一个简单的表。

create table author(auth_id int not null, auth_name varchar(50),topic varchar(100))

Insert Table

创建表后,使用以下查询插入三条记录。

insert into author values(1,'Doug Cutting','Hadoop')
insert into author values(2,’James Gosling','java')
insert into author values(3,'Dennis Ritchie’,'C')

Select Records

要检索所有记录,请键入以下查询。

Query

select * from author

Result

auth_id    auth_name      topic
1        Doug Cutting     Hadoop
2        James Gosling    java
3        Dennis Ritchie     C

截至目前,您已使用 MySQL 服务器查询了数据。我们来将 Mysql 存储插件连接到 Presto 服务器。

Connect Presto CLI

键入以下命令以在 Presto CLI 上连接 MySql 插件。

./presto --server localhost:8080 --catalog mysql --schema tutorials

您将收到以下应答。

presto:tutorials>

此处 “tutorials” 指的是 mysql 服务器中的架构。

List Schemas

要列出 mysql 中的所有架构,请在 Presto 服务器中键入以下查询。

Query

presto:tutorials> show schemas from mysql;

Result

      Schema
--------------------
 information_schema
 performance_schema
 sys
 tutorials

从此结果中,我们可以得出结论,前三个架构是预定义的,最后一个是您自己创建的。

List Tables from Schema

以下查询列出教程架构中的所有表。

Query

presto:tutorials> show tables from mysql.tutorials;

Result

  Table
--------
 author

我们只在此架构中创建了一个表。如果您创建了多个表,它将列出所有表。

Describe Table

要描述表字段,请键入以下查询。

Query

presto:tutorials> describe mysql.tutorials.author;

Result

  Column   |     Type     | Comment
-----------+--------------+---------
 auth_id   | integer      |
 auth_name | varchar(50)  |
 topic     | varchar(100) |

Show Columns from Table

Query

presto:tutorials> show columns from mysql.tutorials.author;

Result

 Column    |     Type     | Comment
-----------+--------------+---------
 auth_id   | integer      |
 auth_name | varchar(50)  |
 topic     | varchar(100) |

Access Table Records

要从 mysql 表获取所有记录,请发出以下查询。

Query

presto:tutorials> select * from mysql.tutorials.author;

Result

auth_id  |   auth_name    | topic
---------+----------------+--------
       1 | Doug Cutting   | Hadoop
       2 | James Gosling  | java
       3 | Dennis Ritchie | C

从此结果中,您可以在 Presto 中检索 mysql 服务器记录。

Create Table Using as Command

Mysql 连接器不支持创建表查询,但可以使用 as 命令创建表。

Query

presto:tutorials> create table mysql.tutorials.sample as
select * from mysql.tutorials.author;

Result

CREATE TABLE: 3 rows

您无法直接插入行,因为此连接器有一些限制。它不支持以下查询:

  1. create

  2. insert

  3. update

  4. delete

  5. drop

要查看新创建表中的记录,请键入以下查询。

Query

presto:tutorials> select * from mysql.tutorials.sample;

Result

auth_id  |   auth_name    | topic
---------+----------------+--------
       1 | Doug Cutting   | Hadoop
       2 | James Gosling  | java
       3 | Dennis Ritchie | C

Apache Presto - JMX Connector

Java Management Extensions (JMX) 提供有关 Java 虚拟机和在 JVM 内部运行的软件的信息。该 JMX 连接器用于在 Presto 服务器中查询 JMX 信息。

由于我们已经启用了 “jmx.properties” 目录下的 “etc/catalog” 文件。现连接 Prest CLI 来启用 JMX 插件。

Presto CLI

Query

$ ./presto --server localhost:8080 --catalog jmx --schema jmx

Result

您将收到以下应答。

presto:jmx>

JMX Schema

要列出 “jmx” 中的所有架构,请键入以下查询。

Query

presto:jmx> show schemas from jmx;

Result

      Schema
--------------------
 information_schema
 current

Show Tables

要查看 “current” 架构中的表,请使用以下命令。

Query 1

presto:jmx> show tables from jmx.current;

Result

                                    Table
------------------------------------------------------------------------------
 com.facebook.presto.execution.scheduler:name = nodescheduler
 com.facebook.presto.execution:name = queryexecution
 com.facebook.presto.execution:name = querymanager
 com.facebook.presto.execution:name = remotetaskfactory
 com.facebook.presto.execution:name = taskexecutor
 com.facebook.presto.execution:name = taskmanager
 com.facebook.presto.execution:type = queryqueue,name = global,expansion = global
 ………………
 ……………….

Query 2

presto:jmx> select * from jmx.current.”java.lang:type = compilation";

Result

node               | compilationtimemonitoringsupported |      name   |         objectname         | totalcompilationti
--------------------------------------+------------------------------------+--------------------------------+----------------------------+-------------------
ffffffff-ffff-ffff-ffff-ffffffffffff | true | HotSpot 64-Bit Tiered Compilers | java.lang:type=Compilation |       1276

Query 3

presto:jmx> select * from jmx.current."com.facebook.presto.server:name = taskresource";

Result

 node                 | readfromoutputbuffertime.alltime.count
 | readfromoutputbuffertime.alltime.max | readfromoutputbuffertime.alltime.maxer
 --------------------------------------+---------------------------------------+--------------------------------------+---------------------------------------
 ffffffff-ffff-ffff-ffff-ffffffffffff |                                   92.0 |                          1.009106149 |

Apache Presto - HIVE Connector

Hive 连接器允许查询存储在 Hive 数据仓库中的数据。

Prerequisites

  1. Hadoop

  2. Hive

希望你在你的机器上安装了 Hadoop 和 Hive。在新终端中逐个启动所有服务。然后,使用以下命令启动 hive 元数据存储,

hive --service metastore

Presto 使用 Hive 元数据存储服务来获取 Hive 表的详细信息。

Configuration Settings

“etc/catalog” 目录下创建一个文件 “hive.properties” 。使用以下命令。

$ cd etc
$ cd catalog
$ vi hive.properties

connector.name = hive-cdh4
hive.metastore.uri = thrift://localhost:9083

完成所有更改后,保存文件并退出终端。

Create Database

使用以下查询在 Hive 中创建数据库:

Query

hive> CREATE SCHEMA tutorials;

创建数据库后,你可以使用 “show databases” 命令进行验证。

Create Table

创建表是用于在 Hive 中创建表的语句。例如,使用以下查询。

hive> create table author(auth_id int, auth_name varchar(50),
topic varchar(100) STORED AS SEQUENCEFILE;

Insert Table

以下查询可用于向 hive 表中插入记录。

hive> insert into table author values (1,’ Doug Cutting’,Hadoop),
(2,’ James Gosling’,java),(3,’ Dennis Ritchie’,C);

Start Presto CLI

你可以启动 Presto CLI 以使用以下命令连接 Hive 存储插件。

$ ./presto --server localhost:8080 --catalog hive —schema tutorials;

您将收到以下应答。

presto:tutorials >

List Schemas

要列出 Hive 连接器中的所有模式,请键入以下命令。

Query

presto:tutorials > show schemas from hive;

Result

default

tutorials

List Tables

要列出“教程”模式中的所有表,请使用以下查询。

Query

presto:tutorials > show tables from hive.tutorials;

Result

author

Fetch Table

以下查询用于从 hive 表中抓取所有记录。

Query

presto:tutorials > select * from hive.tutorials.author;

Result

auth_id  |   auth_name    | topic
---------+----------------+--------
       1 | Doug Cutting   | Hadoop
       2 | James Gosling  | java
       3 | Dennis Ritchie | C

Apache Presto - KAFKA Connector

Presto 的 Kafka 连接器允许使用 Presto 访问 Apache Kafka 中的数据。

Prerequisites

下载并安装最新版本的以下 Apache 项目。

  1. Apache ZooKeeper

  2. Apache Kafka

Start ZooKeeper

使用以下命令启动 ZooKeeper 服务器。

$ bin/zookeeper-server-start.sh config/zookeeper.properties

现在,ZooKeeper 在端口 2181 上启动。

Start Kafka

在另一个终端中使用以下命令启动 Kafka。

$ bin/kafka-server-start.sh config/server.properties

Kafka 启动后,它使用端口号 9092。

TPCH Data

Download tpch-kafka

$  curl -o kafka-tpch
https://repo1.maven.org/maven2/de/softwareforge/kafka_tpch_0811/1.0/kafka_tpch_
0811-1.0.sh

现在你已经使用上述命令从 Maven 中心下载了加载器。你将获得如下的类似响应。

% Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:--  0:00:01 --:--:--     0
  5 21.6M    5 1279k    0     0  83898      0  0:04:30  0:00:15  0:04:15  129k
  6 21.6M    6 1407k    0     0  86656      0  0:04:21  0:00:16  0:04:05  131k
 24 21.6M   24 5439k    0     0   124k      0  0:02:57  0:00:43  0:02:14  175k
 24 21.6M   24 5439k    0     0   124k      0  0:02:58  0:00:43  0:02:15  160k
 25 21.6M   25 5736k    0     0   128k      0  0:02:52  0:00:44  0:02:08  181k
 ………………………..

然后,使用以下命令使其可执行,

$ chmod 755 kafka-tpch

Run tpch-kafka

使用以下命令运行 kafka-tpch 程序来预加载许多带有 tpch 数据的主题。

Query

$ ./kafka-tpch load --brokers localhost:9092 --prefix tpch. --tpch-type tiny

Result

2016-07-13T16:15:52.083+0530 INFO main io.airlift.log.Logging Logging
to stderr
2016-07-13T16:15:52.124+0530 INFO main de.softwareforge.kafka.LoadCommand
Processing tables: [customer, orders, lineitem, part, partsupp, supplier,
nation, region]
2016-07-13T16:15:52.834+0530 INFO pool-1-thread-1
de.softwareforge.kafka.LoadCommand Loading table 'customer' into topic 'tpch.customer'...
2016-07-13T16:15:52.834+0530 INFO pool-1-thread-2
de.softwareforge.kafka.LoadCommand Loading table 'orders' into topic 'tpch.orders'...
2016-07-13T16:15:52.834+0530 INFO pool-1-thread-3
de.softwareforge.kafka.LoadCommand Loading table 'lineitem' into topic 'tpch.lineitem'...
2016-07-13T16:15:52.834+0530 INFO pool-1-thread-4
de.softwareforge.kafka.LoadCommand Loading table 'part' into topic 'tpch.part'...
………………………
……………………….

现在,使用 tpch 加载了 Kafka 表 customers、orders、supplier 等。

Add Config Settings

我们来在 Presto 服务器上添加以下 Kafka 连接器配置设置。

connector.name = kafka

kafka.nodes = localhost:9092

kafka.table-names = tpch.customer,tpch.orders,tpch.lineitem,tpch.part,tpch.partsupp,
tpch.supplier,tpch.nation,tpch.region

kafka.hide-internal-columns = false

在上述配置中,使用 Kafka-tpch 程序加载 Kafka 表。

Start Presto CLI

使用以下命令启动 Presto CLI,

$ ./presto --server localhost:8080 --catalog kafka —schema tpch;

这里 “tpch" 是 Kafka 连接器的模式,你将收到如下的响应。

presto:tpch>

List Tables

以下查询列出了 “tpch” 模式中的所有表。

Query

presto:tpch> show tables;

Result

  Table
----------
 customer
 lineitem
 nation
 orders
 part
 partsupp
 region
 supplier

Describe Customer Table

以下查询描述了 “customer” 表。

Query

presto:tpch> describe customer;

Result

  Column           |  Type   |                   Comment
-------------------+---------+---------------------------------------------
 _partition_id     | bigint  | Partition Id
 _partition_offset | bigint  | Offset for the message within the partition
 _segment_start    | bigint  | Segment start offset
 _segment_end      | bigint  | Segment end offset
 _segment_count    | bigint  | Running message count per segment
 _key              | varchar | Key text
 _key_corrupt      | boolean | Key data is corrupt
 _key_length       | bigint  | Total number of key bytes
 _message          | varchar | Message text
 _message_corrupt  | boolean | Message data is corrupt
 _message_length   | bigint  | Total number of message bytes

Apache Presto - JDBC Interface

Presto 的 JDBC 接口用于访问 Java 应用程序。

Prerequisites

安装 presto-jdbc-0.150.jar

你可以通过访问以下链接下载 JDBC jar 文件,

下载 jar 文件后,将其添加到 Java 应用程序的类路径中。

Create a Simple Application

让我们使用 JDBC 接口创建一个简单的 java 应用程序。

编码 - PrestoJdbcSample.java

import java.sql.*;
import com.facebook.presto.jdbc.PrestoDriver;

//import presto jdbc driver packages here.
public class PrestoJdbcSample {
   public static void main(String[] args) {
      Connection connection = null;
      Statement statement = null;
      try {

         Class.forName("com.facebook.presto.jdbc.PrestoDriver");
         connection = DriverManager.getConnection(
         "jdbc:presto://localhost:8080/mysql/tutorials", "tutorials", “");

         //connect mysql server tutorials database here
         statement = connection.createStatement();
         String sql;
         sql = "select auth_id, auth_name from mysql.tutorials.author”;

         //select mysql table author table two columns
         ResultSet resultSet = statement.executeQuery(sql);
         while(resultSet.next()){
            int id  = resultSet.getInt("auth_id");
            String name = resultSet.getString(“auth_name");
            System.out.print("ID: " + id + ";\nName: " + name + "\n");
         }

         resultSet.close();
         statement.close();
         connection.close();

      }catch(SQLException sqlException){
         sqlException.printStackTrace();
      }catch(Exception exception){
         exception.printStackTrace();
      }
   }
}

保存文件并退出应用程序。现在,在一个终端中启动 Presto 服务器,并打开一个新终端来编译和执行结果。以下是步骤:

Compilation

~/Workspace/presto/presto-jdbc $ javac -cp presto-jdbc-0.149.jar  PrestoJdbcSample.java

Execution

~/Workspace/presto/presto-jdbc $ java -cp .:presto-jdbc-0.149.jar  PrestoJdbcSample

Output

INFO: Logging initialized @146ms
ID: 1;
Name: Doug Cutting
ID: 2;
Name: James Gosling
ID: 3;
Name: Dennis Ritchie

Apache Presto - Custom Function Application

创建一个 Maven 项目来开发 Presto 自定义函数。

SimpleFunctionsFactory.java

创建 SimpleFunctionsFactory 类来实现 FunctionFactory 接口。

package com.tutorialspoint.simple.functions;

import com.facebook.presto.metadata.FunctionFactory;
import com.facebook.presto.metadata.FunctionListBuilder;
import com.facebook.presto.metadata.SqlFunction;
import com.facebook.presto.spi.type.TypeManager;
import java.util.List;

public class SimpleFunctionFactory implements FunctionFactory {

   private final TypeManager typeManager;
   public SimpleFunctionFactory(TypeManager typeManager) {
      this.typeManager = typeManager;
   }
    @Override

   public List<SqlFunction> listFunctions() {
      return new FunctionListBuilder(typeManager)
      .scalar(SimpleFunctions.class)
      .getFunctions();
   }
}

SimpleFunctionsPlugin.java

创建一个 SimpleFunctionsPlugin 类来实现 Plugin 接口。

package com.tutorialspoint.simple.functions;

import com.facebook.presto.metadata.FunctionFactory;
import com.facebook.presto.spi.Plugin;
import com.facebook.presto.spi.type.TypeManager;
import com.google.common.collect.ImmutableList;
import javax.inject.Inject;
import java.util.List;
import static java.util.Objects.requireNonNull;

public class SimpleFunctionsPlugin implements Plugin {
   private TypeManager typeManager;
   @Inject

   public void setTypeManager(TypeManager typeManager) {
      this.typeManager = requireNonNull(typeManager, "typeManager is null”);
      //Inject TypeManager class here
   }
   @Override

   public <T> List<T> getServices(Class<T> type){
      if (type == FunctionFactory.class) {
         return ImmutableList.of(type.cast(new SimpleFunctionFactory(typeManager)));
      }
      return ImmutableList.of();
   }
}

Add Resource File

创建一个在实现包中指定的资源文件。

(com.tutorialspoint.simple.functions.SimpleFunctionsPlugin)

然后移动到资源文件所在的位置 @ /path/to/resource/

然后添加这些更改,

com.facebook.presto.spi.Plugin

pom.xml

将以下这些依赖项添加到 pom.xml 文件。

<?xml version = "1.0"?>
<project xmlns = "http://maven.apache.org/POM/4.0.0"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0
    http://maven.apache.org/xsd/maven-4.0.0.xsd">

   <modelVersion>4.0.0</modelVersion>
   <groupId>com.tutorialspoint.simple.functions</groupId>
   <artifactId>presto-simple-functions</artifactId>
   <packaging>jar</packaging>
   <version>1.0</version>
   <name>presto-simple-functions</name>
   <description>Simple test functions for Presto</description>
   <properties>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
   </properties>
   <dependencies>
      <dependency>
         <groupId>com.facebook.presto</groupId>
         <artifactId>presto-spi</artifactId>
         <version>0.149</version>
      </dependency>
      <dependency>
         <groupId>com.facebook.presto</groupId>
         <artifactId>presto-main</artifactId>
         <version>0.149</version>
      </dependency>
      <dependency>
         <groupId>javax.inject</groupId>
         <artifactId>javax.inject</artifactId>
         <version>1</version>
      </dependency>
      <dependency>
         <groupId>com.google.guava</groupId>
         <artifactId>guava</artifactId>
         <version>19.0</version>
      </dependency>
   </dependencies>
   <build>
      <finalName>presto-simple-functions</finalName>
      <plugins>
      <!-- Make this jar executable -->
         <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <version>2.3.2</version>
         </plugin>
      </plugins>
   </build>
</project>

SimpleFunctions.java

使用 Presto 属性创建一个 SimpleFunctions 类。

package com.tutorialspoint.simple.functions;

import com.facebook.presto.operator.Description;
import com.facebook.presto.operator.scalar.ScalarFunction;
import com.facebook.presto.operator.scalar.StringFunctions;
import com.facebook.presto.spi.type.StandardTypes;
import com.facebook.presto.type.LiteralParameters;
import com.facebook.presto.type.SqlType;

public final class SimpleFunctions {
   private SimpleFunctions() {
   }

   @Description("Returns summation of two numbers")
   @ScalarFunction(“mysum")
   //function name
   @SqlType(StandardTypes.BIGINT)

   public static long sum(@SqlType(StandardTypes.BIGINT) long num1,
   @SqlType(StandardTypes.BIGINT) long num2) {
      return num1 + num2;
   }
}

在创建应用程序之后编译并执行该应用程序。它将生成 JAR 文件。复制该文件并将 JAR 文件移动到目标 Presto 服务器插件目录中。

Compilation

mvn compile

Execution

mvn package

现重启 Presto 服务器并连接 Presto 客户端。然后按照以下说明执行自定义函数应用程序,

$ ./presto --catalog mysql --schema default

Query

presto:default> select mysum(10,10);

Result

 _col0
-------
  20