Apache Zeppelin 的 Cassandra CQL 解释器

名称 类别 描述
%cassandra CassandraInterpreter 提供Apache Cassandra CQL查询语言的解释器

启用Cassandra解释器

在笔记本中,要启用Cassandra解释器,请点击齿轮图标并选择Cassandra

解释器绑定

解释器选择

使用Cassandra解释器

在段落中,使用%cassandra来选择Cassandra解释器,然后输入所有命令。

要访问交互式帮助,请输入 HELP;

交互式帮助

解释器命令

Cassandra 解释器接受以下命令

命令类型 命令名称 描述
帮助命令 HELP 显示交互式帮助菜单
模式命令 DESCRIBE KEYSPACE, DESCRIBE CLUSTER, DESCRIBE TABLES ... 用于描述Cassandra模式的定制命令
选项命令 @consistency, @fetchSize ... 向段落中的所有语句注入运行时选项
预编译语句命令 @prepare, @bind, @remove_prepared 允许您注册一个预编译命令,并通过注入绑定值稍后重新使用
原生CQL语句 所有CQL兼容的语句 (SELECT, INSERT, CREATE, ...) 所有CQL语句都直接针对Cassandra服务器执行

CQL 语句

此解释器与Cassandra支持的任何CQL语句兼容。例如:

INSERT INTO users(login,name) VALUES('jdoe','John DOE');
SELECT * FROM users WHERE login='jdoe';

每个语句应该用分号(;)分隔,除了以下特殊命令:

  1. @prepare
  2. @bind
  3. @remove_prepare
  4. @consistency
  5. @serialConsistency
  6. @timestamp
  7. @fetchSize
  8. @requestTimeOut

多行语句以及同一行上的多个语句也支持,只要它们用分号分隔。例如:

USE spark_demo;

SELECT * FROM albums_by_country LIMIT 1; SELECT * FROM countries LIMIT 1;

SELECT *
FROM artists
WHERE login='jlennon';

支持批处理语句,并且可以跨越多行,以及DDL(CREATE/ALTER/DROP)语句:

BEGIN BATCH
    INSERT INTO users(login,name) VALUES('jdoe','John DOE');
    INSERT INTO users_preferences(login,account_type) VALUES('jdoe','BASIC');
APPLY BATCH;

CREATE TABLE IF NOT EXISTS test(
    key int PRIMARY KEY,
    value text
);

CQL语句是不区分大小写的(除了列名和值)。这意味着以下语句是等效且有效的:

INSERT INTO users(login,name) VALUES('jdoe','John DOE');
Insert into users(login,name) vAlues('hsue','Helen SUE');

所有CQL语句和版本的完整列表可以在下面找到:


Cassandra 版本 文档链接
3.x https://docs.datastax.com/en/archived/cql/3.3/cql/cqlIntro.html
2.2 https://docs.datastax.com/en/archived/cql/3.3/cql/cqlIntro.html
2.1 http://docs.datastax.com/en/cql/3.1/cql/cqlintroc.html

语句中的注释

可以在语句之间添加注释。单行注释以井号#)、双斜杠//)、双破折号--)开头。多行注释则包含在/****/之间。例如:

# Single line comment style 1
INSERT INTO users(login,name) VALUES('jdoe','John DOE');

// Single line comment style 2

// Single line comment style 3

/**
 Multi line
 comments
 **/
Insert into users(login,name) vAlues('hsue','Helen SUE');

语法验证

解释器附带了一个内置的语法验证器。此验证器仅检查基本的语法错误。

所有与CQL相关的语法验证都直接委托给Cassandra

大多数情况下,语法错误是由于语句之间缺少分号拼写错误引起的。

模式命令

为了使模式发现更容易且更具交互性,支持以下命令:

Command Description
DESCRIBE CLUSTER; Show the current cluster name and its partitioner
DESCRIBE KEYSPACES; List all existing keyspaces in the cluster and their configuration (replication factor, durable write ...)
DESCRIBE TABLES; List all existing keyspaces in the cluster and for each, all the tables name
DESCRIBE TYPES; List all existing keyspaces in the cluster and for each, all the user-defined types name
DESCRIBE FUNCTIONS; List all existing keyspaces in the cluster and for each, all the functions name
DESCRIBE AGGREGATES; List all existing keyspaces in the cluster and for each, all the aggregates name
DESCRIBE MATERIALIZED VIEWS; List all existing keyspaces in the cluster and for each, all the materialized views name
DESCRIBE KEYSPACE <keyspacename>; Describe the given keyspace configuration and all its table details (name, columns, ...)
DESCRIBE TABLE (<keyspacename>).<tablename>; Describe the given table. If the keyspace is not provided, the current logged in keyspace is used. If there is no logged in keyspace, the default system keyspace is used. If no table is found, an error message is raised
DESCRIBE TYPE (<keyspacename>).<typename>; Describe the given type(UDT). If the keyspace is not provided, the current logged in keyspace is used. If there is no logged in keyspace, the default system keyspace is used. If no type is found, an error message is raised
DESCRIBE FUNCTION (<keyspacename>).<functionname>; Describe the given function. If the keyspace is not provided, the current logged in keyspace is used. If there is no logged in keyspace, the default system keyspace is used. If no function is found, an error message is raised
DESCRIBE AGGREGATE (<keyspacename>).<aggregatename>; Describe the given aggregate. If the keyspace is not provided, the current logged in keyspace is used. If there is no logged in keyspace, the default system keyspace is used. If no aggregate is found, an error message is raised
DESCRIBE MATERIALIZED VIEW (<keyspacename>).<view_name>; Describe the given view. If the keyspace is not provided, the current logged in keyspace is used. If there is no logged in keyspace, the default system keyspace is used. If no view is found, an error message is raised

模式对象(集群、键空间、表、类型、函数和聚合)以表格形式显示。 左上角有一个下拉菜单,用于展开对象详细信息。右上角菜单显示图标图例。

描述模式

运行时执行参数

有时您希望能够将运行时查询参数传递给您的语句。

这些参数不是CQL规范的一部分,而是特定于解释器的。

以下是所有参数的列表:


参数 语法 描述
一致性级别 @consistency=value 将给定的一致性级别应用于段落中的所有查询
序列一致性级别 @serialConsistency=value 将给定的序列一致性级别应用于段落中的所有查询
时间戳 @timestamp=long value 将给定的时间戳应用于段落中的所有查询。 请注意,直接在CQL语句中传递的时间戳值将覆盖此值
获取大小 @fetchSize=integer value 将给定的获取大小应用于段落中的所有查询
请求超时 @requestTimeOut=integer value 将给定的请求超时以毫秒为单位应用于段落中的所有查询

某些参数仅接受受限值:

参数 可能的值
一致性级别 ALL, ANY, ONE, TWO, THREE, QUORUM, LOCALONE, LOCALQUORUM, EACHQUORUM
序列一致性级别 SERIAL, LOCALSERIAL
时间戳 任何长整型值
获取大小 任何整数值

请注意,您不应在每个参数语句的末尾添加分号(;

一些例子:

CREATE TABLE IF NOT EXISTS spark_demo.ts(
    key int PRIMARY KEY,
    value text
);
TRUNCATE spark_demo.ts;

// Timestamp in the past
@timestamp=10

// Force timestamp directly in the first insert
INSERT INTO spark_demo.ts(key,value) VALUES(1,'first insert') USING TIMESTAMP 100;

// Select some data to make the clock turn
SELECT * FROM spark_demo.albums LIMIT 100;

// Now insert using the timestamp parameter set at the beginning(10)
INSERT INTO spark_demo.ts(key,value) VALUES(1,'second insert');

// Check for the result. You should see 'first insert'
SELECT value FROM spark_demo.ts WHERE key=1;

关于查询参数的一些说明:

  1. 许多查询参数可以在同一段落中设置
  2. 如果相同的查询参数被多次设置不同的值,解释器只会考虑第一个值
  3. 每个查询参数适用于同一段落中的所有CQL语句,除非你使用纯CQL文本覆盖该选项(例如使用USING子句强制时间戳)
  4. 每个查询参数相对于CQL语句的顺序无关紧要

运行时格式化参数

有时您希望能够格式化语句的输出。Cassandra 解释器允许将不同的参数指定为段落的本地属性。以下是所有格式化参数的列表:

Parameter Syntax Description
Output Format outputFormat=value Controls, should we output data as CQL literals, or in human-readable form. Possible values: cql, human (default: human
Locale locale=value Locale for formatting of numbers & time-related values. Could be any locale supported by JVM (default: en_US)
Timezone timezone=value Timezone for formatting of time-related values. Could be any timezone supported by JVM (default: UTC)
Float precision floatPrecision=value Precision when formatting float values. Any positive integer value, or -1 to show everything
Double precision doublePrecision=value Precision when formatting double values. Any positive integer value, or -1 to show everything
Decimal precision decimalPrecision=value Precision when formatting decimal values. Any positive integer value, or -1 to show everything
Timestamp Format timestampFormat=value Format string for timestamp values. Should be valid DateTimeFormatter pattern
Time Format timeFormat=value Format string for time values. Should be valid DateTimeFormatter pattern
Date Format dateFormat=value Format string for date values. Should be valid DateTimeFormatter pattern

一些例子:

create table if not exists zep.test_format (
  id int primary key,
  text text,
  date date,
  timestamp timestamp,
  time time,
  double double,
  float float
);

insert into zep.test_format(id, text, date, timestamp, time, double, float)
  values (1, 'text', '2019-01-29', '2020-06-16T23:59:59.123Z', '04:05:00.234', 
  10.0153423453425634653463466346543, 20.0303443); 
%cassandra(outputFormat=human, locale=de_DE, floatPrecision=2, doublePrecision=4, timeFormat=hh:mma, timestampFormat=MM/dd/yy HH:mm, dateFormat="E, d MMM yy", timezone=Etc/GMT+2)
select id, double, float, text, date, time, timestamp from zep.test_format;

将根据设置输出格式化数据,包括德语区域设置:

id  double   float  text  date           time     timestamp
1   10,0153  20,03  text  Di, 29 Jan 19  04:05AM  06/16/20 21:59

当使用 outputFormat=cql 时,数据被格式化为 CQL 字面量:

id double              float       text    date        time                  timestamp
1  10.015342345342564  20.030344  'text'  '2019-01-29' '04:05:00.234000000'  '2020-06-17T01:59:59.123+02:00'

支持预处理语句

出于性能考虑,最好预先准备语句,然后通过提供绑定值来重复使用它们。

此解释器提供了3个命令来处理准备和绑定的语句:

  1. @prepare
  2. @bind
  3. @remove_prepared

示例:

@prepare[statement-name]=...

@bind[statement-name]=’text’, 1223, ’2015-07-30 12:00:01’, null, true, [‘list_item1’, ’list_item2’]

@bind[statement-name-with-no-bound-value]

@remove_prepare[statement-name]

@prepare

你可以使用语法 "@prepare[statement-name]=SELECT..." 来创建一个预编译语句。 statement-name必需的,因为解释器会使用 Java 驱动程序准备给定的语句,并将生成的预编译语句保存在一个内部哈希映射中,使用提供的 statement-name 作为搜索键。

请注意,这个内部准备好的语句映射与所有笔记本所有段落共享,因为Cassandra的解释器只有一个实例。

如果解释器遇到多个 @prepare 用于相同的语句名称 (键),则只会考虑第一个语句。

示例:

@prepare[select]=SELECT * FROM spark_demo.albums LIMIT ?

@prepare[select]=SELECT * FROM spark_demo.artists LIMIT ?

对于上述示例,预编译语句是 SELECT * FROM spark_demo.albums LIMIT ?SELECT * FROM spark_demo.artists LIMIT ? 被忽略,因为预编译语句映射中已经存在一个键为 select 的条目。

Zeppelin的上下文中,笔记本可以安排定期执行, 因此有必要避免多次重新准备相同的语句(被认为是一种反模式)

@bind

一旦语句准备好(可能在一个单独的笔记本/段落中),你可以将值绑定到它:

@bind[select_first]=10

对于@bind语句,绑定值不是强制性的。但是,如果您提供绑定值,它们需要符合一些语法:

  • 字符串值应包含在单引号之间('
  • 日期值应包含在单引号(')之间,并遵循格式(完整列表在文档中):
    1. yyyy-MM-dd HH:MM:ss
    2. yyyy-MM-dd HH:MM:ss.SSS
    3. yyyy-mm-dd'T'HH:mm:ss.SSSZ
  • null 被原样解析
  • boolean (true|false) 按原样解析
  • 集合值必须遵循标准CQL语法
    • 列表: ['listitem1', 'listitem2', ...]
    • 集合: {'setitem1', 'setitem2', …}
    • 映射: {'key1': 'val1', 'key2': 'val2', …}
  • tuple 值应括在括号内(参见 Tuple CQL 语法):('text', 123, true)
  • udt 值应放在大括号内(参见 UDT CQL 语法):{streename: 'Beverly Hills', number: 104, zipcode: 90020, state: 'California', …}

可以在批处理中使用@bind语句:

BEGIN BATCH
   @bind[insert_user]='jdoe','John DOE'
   UPDATE users SET age = 27 WHERE login='hsue';
APPLY BATCH;

@remove_prepare

为了避免一个准备好的语句永远留在准备好的语句映射中,你可以使用 @remove_prepare[statement-name] 语法来移除它。 移除一个不存在的准备好的语句不会产生错误。

使用动态表单

与其硬编码你的CQL查询,不如使用[Zeppelin动态表单]语法来注入简单的值或多选表单。

传统的mustache语法({{ }})用于绑定输入文本和选择表单仍然受支持,但已被弃用,并将在未来的版本中移除。

旧版 简单参数的语法是:{{input_Label=默认值}}。默认值是必需的,因为第一次执行段落时, 我们在渲染表单之前启动CQL查询,因此至少应提供一个值。

多选参数的语法是:{{input_Label=value1 | value2 | … | valueN }}。默认情况下,第一次执行段落时,CQL查询使用第一个选项。

示例:

#Secondary index on performer style
SELECT name, country, performer
FROM spark_demo.performers
WHERE name='${performer=Sheryl Crow|Doof|Fanfarlo|Los Paranoia}'
AND styles CONTAINS '${style=Rock}';

在上面的例子中,第一个CQL查询将执行performer='Sheryl Crow' AND style='Rock'。 对于后续的查询,您可以直接使用表单更改值。

请注意,我们将${ }块用单引号(')括起来,因为Cassandra在这里期望一个字符串。 我们也可以使用${style='Rock'}语法,但这次表单上显示的值是'Rock'而不是Rock

也可以使用动态表单来创建预编译语句

@bind[select]=='${performer=Sheryl Crow|Doof|Fanfarlo|Los Paranoia}', '${style=Rock}'

共享状态

可以并行执行许多段落。然而,在后端,我们仍然使用同步查询。 异步执行只有在可以在InterpreterResult中返回Future值时才有可能。 这对于Zeppelin项目可能是一个有趣的提议。

最近,Zeppelin 允许你选择解释器的隔离级别(参见 [Interpreter Binding Mode] )。

长话短说,你有3种可用的绑定方式:

  • shared : 所有笔记使用相同的JVM相同的解释器实例
  • scoped : 相同的JVM不同的解释器实例, 每个笔记一个
  • isolated: 不同的JVM 运行一个 单个Interpreter实例,每个笔记一个JVM

使用共享绑定,相同的com.datastax.driver.core.Session对象用于所有笔记和段落。 因此,如果您使用USE keyspace_name;语句登录到一个键空间,它将更改所有当前用户Cassandra解释器的键空间,因为我们只为每个Cassandra解释器实例创建一个com.datastax.driver.core.Session对象。

同样的评论也适用于prepared statement hash map,它由使用相同Cassandra解释器实例的所有用户共享。

当使用scoped绑定时,在同一个JVM中,Zeppelin将创建多个Cassandra解释器实例,因此会有多个com.datastax.driver.core.Session对象。使用此绑定时请注意资源和内存的使用!

isolated 模式是最极端的,它将为每个不同的节点创建尽可能多的 JVM/com.datastax.driver.core.Session 对象。

解释器配置

要配置Cassandra解释器,请转到Interpreter菜单并向下滚动以更改参数。 Cassandra解释器使用的是官方的Datastax Java Driver for Apache Cassandra®,大多数参数用于配置Java驱动程序

以下是解释器支持的配置参数及其默认值。

Property Name Description Default Value
cassandra.cluster Name of the Cassandra cluster to connect to Test Cluster
cassandra.compression.protocol On wire compression. Possible values are: NONE, SNAPPY, LZ4 NONE
cassandra.credentials.username If security is enable, provide the login none
cassandra.credentials.password If security is enable, provide the password none
cassandra.hosts Comma separated Cassandra hosts (DNS name or IP address).
Ex: 192.168.0.12,node2,node3
localhost
cassandra.interpreter.parallelism Number of concurrent paragraphs(queries block) that can be executed 10
cassandra.keyspace Default keyspace to connect to. It is strongly recommended to let the default value and prefix the table name with the actual keyspace in all of your queries system
cassandra.load.balancing.policy Load balancing policy. Default = DefaultLoadBalancingPolicy To Specify your own policy, provide the fully qualify class name (FQCN) of your policy. At runtime the driver will instantiate the policy using class name. DEFAULT
cassandra.max.schema.agreement.wait.second Cassandra max schema agreement wait in second 10
cassandra.pooling.connection.per.host.local Protocol V3 and above default = 1 1
cassandra.pooling.connection.per.host.remote Protocol V3 and above default = 1 1
cassandra.pooling.heartbeat.interval.seconds Cassandra pool heartbeat interval in secs 30
cassandra.pooling.max.request.per.connection Protocol V3 and above default = 1024 1024
cassandra.pooling.pool.timeout.millisecs Cassandra pool time out in millisecs 5000
cassandra.protocol.version Cassandra binary protocol version (V3, V4, ...) DEFAULT (detected automatically)
cassandra.query.default.consistency Cassandra query default consistency level
Available values: ONE, TWO, THREE, QUORUM, LOCAL_ONE, LOCAL_QUORUM, EACH_QUORUM, ALL
ONE
cassandra.query.default.fetchSize Cassandra query default fetch size 5000
cassandra.query.default.serial.consistency Cassandra query default serial consistency level
Available values: SERIAL, LOCAL_SERIAL
SERIAL
cassandra.reconnection.policy Cassandra Reconnection Policy. Default = ExponentialReconnectionPolicy To Specify your own policy, provide the fully qualify class name (FQCN) of your policy. At runtime the driver will instantiate the policy using class name. DEFAULT
cassandra.retry.policy Cassandra Retry Policy. Default = DefaultRetryPolicy To Specify your own policy, provide the fully qualify class name (FQCN) of your policy. At runtime the driver will instantiate the policy using class name. DEFAULT
cassandra.socket.connection.timeout.millisecs Cassandra socket default connection timeout in millisecs 500
cassandra.socket.read.timeout.millisecs Cassandra socket read timeout in millisecs 12000
cassandra.socket.tcp.no_delay Cassandra socket TCP no delay true
cassandra.speculative.execution.policy Cassandra Speculative Execution Policy. Default = NoSpeculativeExecutionPolicy To Specify your own policy, provide the fully qualify class name (FQCN) of your policy. At runtime the driver will instantiate the policy using class name. DEFAULT
cassandra.ssl.enabled Enable support for connecting to the Cassandra configured with SSL. To connect to Cassandra configured with SSL use true and provide a truststore file and password with following options. false
cassandra.ssl.truststore.path Filepath for the truststore file to use for connection to Cassandra with SSL.
cassandra.ssl.truststore.password Password for the truststore file to use for connection to Cassandra with SSL.
cassandra.format.output Output format for data - strict CQL (cql), or human-readable (human) human
cassandra.format.locale Which locale to use for output (any locale supported by JVM could be specified) en_US
cassandra.format.timezone For which timezone format time/date-related types (any timezone supported by JVM could be specified) UTC
cassandra.format.timestamp Format string for timestamp columns (any valid DateTimeFormatter pattern could be used) yyyy-MM-dd'T'HH:mm:ss.SSSXXX
cassandra.format.time Format string for time columns (any valid DateTimeFormatter pattern could be used) HH:mm:ss.SSS
cassandra.format.date Format string for date columns (any valid DateTimeFormatter pattern could be used) yyyy-MM-dd
cassandra.format.float_precision Precision when formatting values of float type 5
cassandra.format.double_precision Precision when formatting values of double type 12
cassandra.format.decimal_precision Precision when formatting values of decimal type -1 (show everything)

除了这些参数外,还可以通过将它们添加到解释器配置中来设置其他驱动程序参数。配置键应具有完整形式,并带有datastax-java-driver前缀,如文档中所述。例如,要指定5秒的请求超时,可以使用datastax-java-driver.basic.request.timeout,其值为5 seconds。完整的可用配置选项列表可在文档中查看。额外的选项可能会覆盖由解释器配置参数指定的选项。

变更日志

4.0 (Zeppelin 0.11.2) :

  • 重构以使用统一的Java驱动程序4.7 (ZEPPELIN-4378:
    • 配置中的更改是必要的,因为新驱动程序具有不同的架构和配置选项
    • 解释器获得了对DSE特定数据类型和其他扩展的支持
    • 移除了对@retryPolicy的支持,因为驱动程序只附带了一个重试策略
    • 允许指定Java驱动程序的任何配置选项
    • 放弃了对Cassandra 1.2和2.0的支持,因为驱动程序不再支持这些版本
  • 添加了对格式化选项的支持,包括解释器和单元格级别

3.1 (Zeppelin 0.11.2) :

3.0 (Zeppelin 0.11.2) :

  • 更新文档
  • 更新交互式文档
  • 添加对二进制协议 V4 的支持
  • 实现新的@requestTimeOut运行时选项
  • 将Java驱动程序版本升级到3.0.1
  • 允许解释器在使用FormType.SIMPLE时以编程方式添加动态表单
  • 允许使用默认的Zeppelin语法进行动态表单
  • 修复了FallThroughPolicy上的拼写错误
  • 在创建动态表单之前,先在AngularObjectRegistry中查找数据
  • 添加对ALTER语句的缺失支持

2.0 (Zeppelin 0.11.2) :

  • 更新帮助菜单并添加变更日志
  • 添加对用户定义函数用户定义聚合物化视图的支持
  • 将Java驱动程序版本升级到3.0.0-rc1

1.0 (Zeppelin 0.5.5-incubating) :

  • 初始版本

错误与联系

如果您遇到此解释器的错误,请创建一个JIRA工单。

Zeppelin 动态表单 解释器绑定模式