添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

Databricks SQL Driver for Node.js 是一个 Node.js 库,它让你可以使用 JavaScript 代码在 Azure Databricks 计算资源上运行 SQL 命令。

  • 运行 Node.js 版本 14 或更高版本的开发计算机。 若要输出已安装的 Node.js 版本,请运行命令 node -v 。 若要安装和使用其他版本的 Node.js,可以使用 Node 版本管理器 (nvm) 等工具。

  • Node 包管理器 ( npm )。 较新版本的 Node.js 已包含 npm 。 若要检查是否已安装 npm ,请运行命令 npm -v 。 若要根据需要安装 npm ,可以按照 下载并安装 npm 中的说明进行操作。

  • 来自 npm 的 @databricks/sql 包。 若要将 @databricks/sql 包作为依赖项安装到 Node.js 项目中,请使用 npm 从与项目相同的目录中运行以下命令:

    npm i @databricks/sql
    
  • 如果希望将 TypeScript 安装到 Node.js 项目中并将其用作 devDependencies,请使用 npm 从与项目相同的目录中运行以下命令:

    npm i -D typescript
    npm i -D @types/node
    
  • 现有群集或 SQL 仓库。

  • 显示分类。
  • 创建群集。
  • 查看 SQL 仓库。
  • 创建 SQL 仓库。
  • 现有群集或 SQL 仓库的“服务器主机名”和“HTTP 路径”值。

  • 获取群集的这些值。
  • 获取 SQL 仓库的这些值。
  • 一个 Azure Databricks 个人访问令牌。

  • 管理个人访问令牌。
  • Databricks SQL Driver for Node.js 不支持将 Azure Active Directory (Azure AD) 令牌用于身份验证。

    指定连接变量

    若要访问群集或 SQL 仓库,Databricks SQL Driver for Node.js 使用名为 token、server_hostname 和 http_path 的连接变量,分别表示 Azure Databricks 个人访问令牌以及群集或 SQL 仓库的“服务器主机名”和“HTTP 路径”值。

    token 的 Azure Databricks 个人访问令牌值类似于以下内容:dapi1ab2c34defabc567890123d4efa56789。

    作为 server_hostname 的服务器主机名值类似于以下内容:adb-1234567890123456.7.azuredatabricks.net。

    作为 http_path 的 HTTP 路径值类似于以下内容:sql/protocolv1/o/1234567890123456/1234-567890-abcdefgh(适用于群集)、/sql/1.0/endpoints/a1b234c5678901d2(适用于 SQL 仓库)。

    作为安全最佳做法,不应将这些连接变量值硬编码到代码中。 而应从安全位置检索这些连接变量值。 例如,本文后面的代码示例使用了环境变量。

    下面的代码示例演示如何调用 Databricks SQL Driver for Node.js 以在 Azure Databricks 计算资源上运行基本 SQL 查询。 此命令返回 diamonds 表中的前两行。

    diamonds 表将包含在示例数据集中。

    此代码示例从一组 Azure Databricks 环境变量中检索 token、server_hostname 和 http_path 连接变量值。 这些环境变量具有以下环境变量名称:

  • DATABRICKS_TOKEN,表示要求中的 Azure Databricks 个人访问令牌。
  • DATABRICKS_SERVER_HOSTNAME,表示要求中的“服务器主机名”值。
  • DATABRICKS_HTTP_PATH,表示要求中的“HTTP 路径”值。
  • 可以使用其他方法来检索这些连接变量值。 使用环境变量只是众多方法中的一种。

    以下代码示例演示如何调用适用于 Node.js 的 Databricks SQL 连接器在群集或 SQL 仓库上运行基本 SQL 命令。 此命令返回菱形表中的前两行。

    Javascript

    const { DBSQLClient } = require('@databricks/sql');
    var token          = process.env.DATABRICKS_TOKEN;
    var serverHostname = process.env.DATABRICKS_SERVER_HOSTNAME;
    var httpPath       = process.env.DATABRICKS_HTTP_PATH;
    if (!token || !serverHostname || !httpPath) {
      throw new Error("Cannot find Server Hostname, HTTP Path, or personal access token. " +
                      "Check the environment variables DATABRICKS_TOKEN, " +
                      "DATABRICKS_SERVER_HOSTNAME, and DATABRICKS_HTTP_PATH.");
    const client = new DBSQLClient();
    client.connect(
      options = {
        token: token,
        host:  serverHostname,
        path:  httpPath
      }).then(
        async client => {
          const session = await client.openSession();
          const queryOperation = await session.executeStatement(
            statement = 'SELECT * FROM default.diamonds LIMIT 2',
            options   = {
              runAsync: true,
              maxRows: 10000 // This option enables the direct results feature.
          const result = await queryOperation.fetchAll({
            progress: false,
            callback: () => {},
          await queryOperation.close();
          console.table(result);
          await session.close();
          await client.close();
    }).catch((error) => {
      console.log(error);
    

    Typescript

    import { DBSQLClient } from '@databricks/sql';
    import IDBSQLSession from '@databricks/sql/dist/contracts/IDBSQLSession';
    import IOperation from '@databricks/sql/dist/contracts/IOperation';
    var serverHostname: string = process.env.DATABRICKS_SERVER_HOSTNAME || '';
    var httpPath: string       = process.env.DATABRICKS_HTTP_PATH || '';
    var token: string          = process.env.DATABRICKS_TOKEN || '';
    if (serverHostname == '' || httpPath == '' || token == '') {
      throw new Error("Cannot find Server Hostname, HTTP Path, or personal access token. " +
                      "Check the environment variables DATABRICKS_SERVER_HOSTNAME, " +
                      "DATABRICKS_HTTP_PATH, and DATABRICKS_TOKEN.");
    const client: DBSQLClient = new DBSQLClient();
    client.connect(
        host:  serverHostname,
        path:  httpPath,
        token: token
      }).then(
        async client => {
          const session: IDBSQLSession = await client.openSession();
          const queryOperation: IOperation = await session.executeStatement(
            'SELECT * FROM default.diamonds LIMIT 2',
              runAsync: true,
              maxRows: 10000 // This option enables the direct results feature.
          const result = await queryOperation.fetchAll({
            progress: false,
            callback: () => {},
          await queryOperation.close();
          console.table(result);
          await session.close();
          client.close();
    }).catch((error) => {
      console.log(error);
    
    ┌─────────┬─────┬────────┬───────────┬───────┬─────────┬────────┬───────┬───────┬────────┬────────┬────────┐
    │ (index) │ _c0 │ carat  │    cut    │ color │ clarity │ depth  │ table │ price │   x    │   y    │   z    │
    ├─────────┼─────┼────────┼───────────┼───────┼─────────┼────────┼───────┼───────┼────────┼────────┼────────┤
    │    0    │ '1' │ '0.23' │  'Ideal'  │  'E'  │  'SI2'  │ '61.5' │ '55'  │ '326' │ '3.95' │ '3.98' │ '2.43' │
    │    1    │ '2' │ '0.21' │ 'Premium' │  'E'  │  'SI1'  │ '59.8' │ '61'  │ '326' │ '3.89' │ '3.84' │ '2.31' │
    └─────────┴─────┴────────┴───────────┴───────┴─────────┴────────┴───────┴───────┴────────┴────────┴────────┘
    

    配置日志记录

    记录器提供有关调试连接器问题的信息。 所有 DBSQLClient 对象都使用打印到控制台的记录器进行实例化,但通过传入自定义记录器,可以将此信息发送到文件。 以下示例演示如何配置记录器并更改其级别。

    Javascript

    const { DBSQLClient, DBSQLLogger, LogLevel } = require('@databricks/sql');
    var token          = process.env.DATABRICKS_TOKEN;
    var serverHostname = process.env.DATABRICKS_SERVER_HOSTNAME;
    var httpPath       = process.env.DATABRICKS_HTTP_PATH;
    if (!token || !serverHostname || !httpPath) {
      throw new Error("Cannot find Server Hostname, HTTP Path, or personal access token. " +
                      "Check the environment variables DATABRICKS_TOKEN, " +
                      "DATABRICKS_SERVER_HOSTNAME, and DATABRICKS_HTTP_PATH.");
    const logger = new DBSQLLogger({ filepath: 'log.txt', level: LogLevel.info });
    const client = new DBSQLClient({ logger: logger });
    client.connect(
      options = {
        token: token,
        host:  serverHostname,
        path:  httpPath
      }).then(
        async client => {
          const session = await client.openSession();
          let queryOperation = await session.executeStatement('SELECT "Hello, World!"', { runAsync: true });
          const result = await queryOperation.fetchAll();
          await queryOperation.close();
          console.table(result);
          // Set logger to different level.
          logger.setLevel(LogLevel.debug);
          queryOperation = await session.executeStatement('SELECT "Hello, World!"', { runAsync: true });
          result = await queryOperation.fetchAll();
          await queryOperation.close();
          await session.close();
          await client.close();
    }).catch((error) => {
      console.log(error);
    

    Typescript

    import { DBSQLClient } from '@databricks/sql';
    import IDBSQLSession from '@databricks/sql/dist/contracts/IDBSQLSession';
    import IOperation from '@databricks/sql/dist/contracts/IOperation';
    var serverHostname: string = process.env.DATABRICKS_SERVER_HOSTNAME || '';
    var httpPath: string       = process.env.DATABRICKS_HTTP_PATH || '';
    var token: string          = process.env.DATABRICKS_TOKEN || '';
    if (serverHostname == '' || httpPath == '' || token == '') {
      throw new Error("Cannot find Server Hostname, HTTP Path, or personal access token. " +
                      "Check the environment variables DATABRICKS_SERVER_HOSTNAME, " +
                      "DATABRICKS_HTTP_PATH, and DATABRICKS_TOKEN.");
    const client: DBSQLClient = new DBSQLClient();
    client.connect(
        host:  serverHostname,
        path:  httpPath,
        token: token
      }).then(
        async client => {
          const session: IDBSQLSession = await client.openSession();
          let queryOperation: IOperation = await session.executeStatement('SELECT "Hello, World!"', { runAsync: true });
          const result = await queryOperation.fetchAll();
          await queryOperation.close();
          console.table(result);
          // Set logger to different level.
          logger.setLevel(LogLevel.debug);
          queryOperation = await session.executeStatement('SELECT "Hello, World!"', { runAsync: true });
          result = await queryOperation.fetchAll();
          await queryOperation.close();
          await session.close();
          await client.close();
    }).catch((error) => {
      console.log(error);
    

    有关其他示例,请参阅 GitHub 上的 databricks/databricks-sql-nodejs 存储库中的 examples 文件夹。

  • GitHub 上的 Databricks SQL Driver for Node.js 存储库
  • Databricks SQL Driver for Node.js 入门
  • Databricks SQL Driver for Node.js 故障排除
  • API 参考

  • DBSQLClient 类

    返回:Promise<IDBSQLSession>

    getClient 方法

    返回内部 thrift TCLIService.Client 对象。 必须在 DBSQLClient 连接后调用。

    返回 TCLIService.Client

    close 方法

    关闭与数据库的连接,并释放服务器上所有关联的资源。 对此客户端的任何其他调用都将引发错误。

    没有返回值。

    DBSQLSession 类

    DBSQLSession 主要用于执行针对数据库的语句以及各种元数据提取操作。

    executeStatement 方法

    使用提供的选项执行语句。

    options

    类型:ExecuteStatementOptions

    一组可选参数,用于确定查询超时、直接结果的最大行数以及是否异步运行查询。 默认情况下,maxRows 设置为 10000。 如果 maxRows 设置为 null,操作将在直接结果功能关闭的情况下运行。

    示例:


    const session = await client.openSession(
    {initialCatalog: 'catalog'}
    );

    queryOperation = await session.executeStatement(
    'SELECT "Hello, World!"', { runAsync: true }
    );

    返回:Promise<IOperation>

    close 方法

    关闭会话。 必须在使用对话后完成。

    没有返回值。

    getId 方法

    返回对话的 GUID。

    返回:str

    getTypeInfo 方法

    返回关于支持数据类型的信息。

    返回:Promise<IOperation>

    DBSQLOperation 类

    DBSQLOperations 由 DBSQLSessions 创建,可用于提取语句的结果并检查其执行情况。 数据通过函数 fetchChunk 和 fetchAll 提取。

    getId 方法

    返回操作的 GUID。

    返回:str

    fetchAll 方法

    等待操作完成,然后从操作中提取所有行。

    返回:Promise<Array<object>>

    fetchChunk 方法

    等待操作完成,然后从操作中提取最多指定数量的行。

  •