文章目录
- 前言
- 一、Sqoop概述
-
- [(一) 什么是Sqoop?](#(一) 什么是Sqoop?)
- [(二)Sqoop workflow](#(二)Sqoop workflow)
- [(三) 核心功能](#(三) 核心功能)
- [(三) Sqoop1与Sqoop2对比](#(三) Sqoop1与Sqoop2对比)
- (四)工作原理
- (五)scenario
-
- [1.Big data analysis 大数据分析](#1.Big data analysis 大数据分析)
- [2.Data migration and synchronization 数据迁移与同步](#2.Data migration and synchronization 数据迁移与同步)
- [3.ETL process ETL过程](#3.ETL process ETL过程)
- [4.Data warehouse construction 数据仓库构建](#4.Data warehouse construction 数据仓库构建)
- [5.Provide data for the data application layer 为数据应用层提供数据](#5.Provide data for the data application layer 为数据应用层提供数据)
- [二、Sqoop tools](#二、Sqoop tools)
-
- [(一)Help tools](#(一)Help tools)
- [(二)Tool aliases](#(二)Tool aliases)
- [(三)Versioning Tools](#(三)Versioning Tools)
- [(四)Listing database tools](#(四)Listing database tools)
- [(五)List all table tools](#(五)List all table tools)
- [(六)Generic Hadoop options](#(六)Generic Hadoop options)
- [三、Sqoop import tool](#三、Sqoop import tool)
-
- (一)数据库连接参数
- [(二)Select Import data](#(二)Select Import data)
-
- [1.Import control arguments](#1.Import control arguments)
- [2. 高频考点分类](#2. 高频考点分类)
-
- (1)**性能优化类参数**(考试重点)
- [(2) **数据选择类参数**(必考)](#(2) 数据选择类参数(必考))
- (3)**文件格式类参数**(理解差异)
-
- [4. **空值处理参数**(易错点)](#4. 空值处理参数(易错点))
- 3.基本导入
- 4.选择性导入
- [5.Free-form Query Imports](#5.Free-form Query Imports)
- [(三)Controlling Parallelism](#(三)Controlling Parallelism)
- [(四)Incremental imports](#(四)Incremental imports)
- [(五)Import file format of choice](#(五)Import file format of choice)
-
- [1.file format to import](#1.file format to import)
- 2.控制参数
- 3.特殊的转义字符
- [4.The default delimiters](#4.The default delimiters)
- [5.Input analytical parameters](#5.Input analytical parameters)
- 6.其他数据文件格式
- [(六)Importing Data into Hive](#(六)Importing Data into Hive)
- [(七)Importing Data into HBase](#(七)Importing Data into HBase)
- [(八)Import Results Validation](#(八)Import Results Validation)
- [(九)The import performance optimization](#(九)The import performance optimization)
-
- [1. Map 任务数量设置](#1. Map 任务数量设置)
- [2.fetch size](#2.fetch size)
- [3.--direct mode](#3.--direct mode)
- [四、Sqoop export tool](#四、Sqoop export tool)
-
- [(一)export arguments](#(一)export arguments)
- [(二)Insert mode and update the model](#(二)Insert mode and update the model)
- [(三)Invocation pattern(call mode)](#(三)Invocation pattern(call mode))
- [(四)Export and Transaction](#(四)Export and Transaction)
- [(五)Export Failure Handling](#(五)Export Failure Handling)
- [(六)Exporting Data from Hive](#(六)Exporting Data from Hive)
- [(七)Exporting Data from HBase](#(七)Exporting Data from HBase)
- [(八)Export Results Validation](#(八)Export Results Validation)
- [(九)The export performance optimization](#(九)The export performance optimization)
- [五、Sqoop job tools](#五、Sqoop job tools)
-
- (一)参数介绍
-
- 1.参数详情
- 2.语法
- 3.实例
- 4.有关命令模板
- 5.作业存储位置
- 6.--meta--connect
-
- (1)参数详情
- [(2) 存储配置属性](#(2) 存储配置属性)
- (3)元数据存储服务管理命令
- [(二)sqoop merge tool](#(二)sqoop merge tool)
- [(三)Sqoop Code Generation Tool](#(三)Sqoop Code Generation Tool)
- 总结
前言
Apache Sqoop是一个功能强大的工具,旨在有效地在Hadoop生态系统和结构化数据存储(如关系数据库)之间传输批量数据 。 它允许用户从外部数据库导入数据到HDFS、Hive或HBase中,反之亦然。 Sqoop自动化了导入和导出数据的过程,减少了手工编码的需要,并确保了传输过程中的数据一致性。 它支持增量加载,只允许导入新的或更新的数据。 Sqoop还提供数据压缩和分割功能,这有助于在大数据传输期间优化性能。 通过其命令行界面,用户可以轻松地定义和执行数据传输作业。 此外,Sqoop与各种Hadoop组件集成得很好,使其成为企业环境中管理大数据的通用工具。
一、Sqoop概述
(一) 什么是Sqoop?
Apache Sqoop是一个用**于在Hadoop分布式文件系统(HDFS)**和关系型数据库管理系统(RDBMS)之间进行高效批量数据传输的工具。
Sqoop旨在简化数据导入和导出的过程,使开发人员可以轻松地将关系数据库中的结构化数据导入到HDFS或HBase中,再将数据从HDFS或HBase导出到关系数据库中。
Sqoop is designed to simplify the process of data import and export, so that developers can easily import data from structured data in relational databases to Hadoop Distributed File System (HDFS) or HBase, and in turn, export data from Hadoop Distributed File System (HDFS) or HBase to relational databases.
关键特性:
- 2012年3月成为Apache顶级项目
- Sqoop将从Apache基金会"退役",并于2021年6月作为子项目迁移到Apache Attic项目。
- 支持HDFS、Hive、HBase等Hadoop生态组件
- 支持MySQL、Oracle、PostgreSQL等主流数据库
- 开源工具,广泛用于大数据生态系统
(二)Sqoop workflow

(三) 核心功能
| 功能 | 描述 | 命令示例 |
|---|---|---|
| 数据导入 | 从RDBMS导入数据到HDFS | sqoop import --connect jdbc:mysql://localhost/db --table employees |
| 数据导出 | 从HDFS导出数据到RDBMS | sqoop export --connect jdbc:mysql://localhost/db --table employees --export-dir /data |
(三) Sqoop1与Sqoop2对比
Sqoop有两个主要版本,称为Sqoop1和Sqoop2。 这两个版本可以通过它们的版本号来区分,sqooop1的版本号是1.4。 最新的稳定版本是1.4.7,sqooop2的版本是1.99。 最新的版本是1.99.7。
1.整体对比
| 特性 | Sqoop1 | Sqoop2 |
|---|---|---|
| 架构 | Connector-based,简单易部署 | 引入Sqoop Server,集中化管理 |
| 访问方式 | 仅命令行(CLI) | CLI、Web UI、REST API |
| 安全性 | 较差,客户端直连 | 基于角色的安全机制 |
| 生产环境 | 适用 | 早期版本特性不完整 |
| 主要缺点 | 参数易错、类型映射不明确 | 架构复杂、配置困难 |
2.Sqoop1
(1)advantage
- Connector-based, simple architecture, easy to deploy.基于连接器,该体系结构易于部署
- Can be used in production environment.能在生产环境中使用
(2)disadvantage
- Can only be called by CLI (command line), errors often happen when using wrong parameters 它只能通过CLI(命令行)调用,并且参数的使用很容易出错
- Unclear type mapping definition 类型映射定义不清楚
- Security concerns 安全机制不完善
- The sqoop client needs to connect directly to Hadoop and the database. 客户端需要直接连接Hadoop和数据库
- The Connector must conform to the JDBC model. 连接器必须符合JDBC模型
3.Sqoop2
(1)advantage
- 引入Sqoop Server以方便集中管理连接器或其他第三方插件
- Introduce Sqoop Server to facilitate centralized management of connectors or other third-party plug-ins
- 支持多种访问方式 :
CLI、Web UI、REST API - Support for multiple access method: CLI, Web UI, REST API
- 引入了基于角色的安全机制 ,管理员可以在sqoop Server上配置不同的角色
- A role-based security mechanism is introduced, and administrators can configure different roles on sqoop Server
(2)disadvantage
- Slightly complex architecture 稍微复杂的体系结构
- Cumbersome to configure and deploy 配置和部署都很麻烦
- Features are incomplete 功能不完整
- Cannot be used in a production environment 无法在生产环境中使用
(四)工作原理
1.工作流
Sqoop主要提供从关系型数据库导入数据到Hadoop(如HDFS、Hive、HBase)的import实用程序 。 Sqoop还提供了一个导出实用程序,用于将数据从Hadoop导出到关系数据库。 下图展示了Sqoop导入和导出的工作流程:
Sqoop primarily provides the import utility for importing data from relational databases into Hadoop, such as HDFS, Hive, or HBase. Sqoop also provides an export utility to export data from Hadoop to a relational database.The following diagram illustrates the workflow of Sqoop imports and exports:

2.工作原理
(1)how sqoop works
Sqoop的工作原理是将导入或导出命令转换为MapReduce程序 。 在翻译程序中主要是针对InputFormat和OutputFormat进行定制。 由于这种工作机制,Sqoop可以利用mapreduce的并行性和容错性来实现导入和导出操作。
Sqoop works by translating import or export commands into MapReduce programs. In the translation of the program is mainly for InputFormat and OutputFormat customization. Because of this working mechanism, Sqoop can use the parallelism and fault tolerance ofMapReduce to implement import and export operations.
(2)import principle
Sqoop - import实用程序,将单个表从RDBMS导入HDFS 。 表中的每一行 在HDFS中表示为一条记录 。 记录可以存储为文本文件(文本行作为记录) ,也可以存储为Avro或SequenceFile数据格式的二进制表示形式。 另一个sqoop - import - all - tables工具可以将RDBMS中的多个表导入到HDFS中,每个表中的数据都存储到单独的文件夹中。 Sqoop -导入工具的导入方式包括:
Sqoop - import utility to a single table from the RDBMS import into HDFS. Each row in the table are represented as a single record in the HDFS. Record can be stored as a text file (lines of text as a record), or stored in binary representation form for Avro or SequenceFile data format. Another sqoop - import - all - tables tools can be a from RDBMS into multiple tables to the HDFS, each table of data are stored to a separate folder. Sqoop - import tool import way include:
- All import volumes: import volume data.
- Import: import parts or partial line.
- Incremental imports: Import only the new data.
(3)export principle
sqoop导出工作原理:sqoop-export工具用于将一组文件从HDFS导出回RDBMS。 当前目标表必须已经存在于数据库 中。 Sqoop导出工具根据用户指定的分隔符 读取输入文件,并将其解析为一组记录。 sqoop-export工具可以通过以下方式导出:
- INSERT mode: The default action is to insert data from a file into a table using an INSERT statement. 默认操作是使用insert语句将数据从文件插入到表中。
- UPDATE mode: Sqoop will generate an UPDATE statement to replace existing records in a database. Sqoop将生成一个UPDATE语句来替换数据库中的现有记录。
- Call mode: Sqoop will create a stored procedure call for each record. Sqoop将为每条记录创建一个存储过程调用。
(五)scenario
1.Big data analysis 大数据分析
在分析大数据时,Sqoop可以使用Hadoop生态系统中的工具(如Hive、Pig、Spark等),将关系型数据库中的数据导入HDFS或HBase中进行分析。
When analyzing big data, Sqoop can import data from relational databases to HDFS or HBase for analysis using tools in the Hadoop ecosystem (such as Hive, Pig, Spark, etc.).
2.Data migration and synchronization 数据迁移与同步
除了作为数据迁移工具,Sqoop还可以用于在关系数据库和Hadoop之间同步数据,以确保两个系统之间的数据一致性。
In addition to being used as a data migration tool, Sqoop can also be used to
synchronize data between relational databases and Hadoop to ensure data consistency between the two systems.
3.ETL process ETL过程
在ETL (Extract, Transform, Load)过程中,Sqoop可以作为数据提取工具,从源系统中提取数据到Hadoop系统中。 在数据加载过程中也可以使用Sqoop将Hadoop系统中的数据导出到关系数据库中。
In the ETL (Extract, Transform, Load) process, Sqoop can be used as a data extraction tool to extract data from the source system to the Hadoop system. Sqoop can also be used in the data loading process to export the data in the Hadoop system to the relational database.
4.Data warehouse construction 数据仓库构建
Sqoop通常用于将数据从关系数据库导入到Hadoop生态系统中,以构建数据仓库。 这样可以对数据进行更深入的分析和处理。
Sqoop is often used to import data from relational databases into the Hadoop ecosystem
for data warehouse construction. This enables more in-depth analysis and processing of data.
5.Provide data for the data application layer 为数据应用层提供数据
Sqoop还可以将Hadoop文件系统中的分析结果导出到MySQL等关系数据库中,为数据应用层提供数据,进一步实现大数据可视化等功能。
Sqoop can also export the analysis results in the Hadoop file system to relational databases such as MySQL, provide data for the data application layer, and further realize big data visualization and other functions.
二、Sqoop tools
Sqoop本身是Sqoop工具的集合,使用Sqoop意味着使用Sqoop提供的所有工具。 要使用Sqoop的函数,需要使用命令中指定的名称和控制工具的参数。 在继续学习更复杂的导入和导出工具之前,您可以使用一些更简单的工具来帮助您理解Sqoop工具的概念以及如何使用它们。
Sqoop itself is a collection ofSqoop tools, and using Sqoop means using all of the tools Sqoop provides. To use a function of Sqoop, need to tool to use the name specified in the command and control the parameters of the tool.
除了显示版本信息的Sqoop -version工具之外,还有显示帮助信息的Sqoop -help工具,Sqoop还提供了一些命令来检查正在使用哪个数据库。 例如,使用sqoop - list - databases工具可以指定数据库中列出服务中所有可用的数据库名称,使用sqoop - list - tables工具可以列出数据库中指定的所有表名称。
Before moving on to the more complex import and export tools, you can use some of the simpler tools to help you understand the concepts of Sqoop tools and how to use them. In addition to the sqoop-version tool, which displays version information,there is also sqoop-help, which displays help information, and Sqoop provides a few commands to check which database is in use. For example, using sqoop - list - databases tool can specify the database listed in the service of all available database name, use sqoop - list - tables tools can list all the tables in the database name specified.
(一)Help tools
首先,Sqoop附带了一个帮助工具。 要显示所有可用工具的列表,请键入以下命令:
First, Sqoop comes with a help tool. To display a list of all available tools, please type the following command:
sql
# 常用Sqoop工具
codegen # 生成与数据库交互的代码
create-hive-table # 将表定义导入Hive
eval # 执行SQL语句并显示结果
export # 从HDFS导出到数据库
import # 从数据库导入到HDFS
import-all-tables # 导入所有表到HDFS
job # 管理保存的作业
list-databases # 列出所有数据库
list-tables # 列出所有表
merge # 合并增量导入结果
metastore # 运行元数据存储
version # 显示版本信息
例如,另一种方法是在命令的末尾添加-help,以达到相同的效果
sql
sqoop import -help
(二)Tool aliases
除了使用sqoop (toolname)命令外,还可以使用名为sqoop-(toolname)的别名脚本。 这些脚本位于Sqoop安装目录的bin目录中:
In addition to using the sqoop (toolname) command, you can also use alias scripts named sqoop-(toolname). These scripts are located in the bin directory of the Sqoop installation directory:
1.具体命令
sql
# 常用Sqoop工具
sqoop-codegen # 生成与数据库交互的代码
sqoop-create-hive-table # 将表定义导入Hive
sqoop-eval # 执行SQL语句并显示结果
sqoop-export # 从HDFS导出到数据库
sqoop-import # 从数据库导入到HDFS
sqoop-import-all-tables # 导入所有表到HDFS
sqoop-job # 管理保存的作业
sqoop-list-databases # 列出所有数据库
sqoop-list-tables # 列出所有表
sqoop-merge # 合并增量导入结果
sqoop-metastore # 运行元数据存储
sqoop-version # 显示版本信息
2.好处
使用别名脚本的好处是,您可以在sqoop中键入命令,然后通过按两次[tab]键自动完成命令,从而避免了输入错误。
The benefit ofusing alias scripts is that you can type commands into sqoop- and then auto-complete them by pressing the [tab]key twice, avoiding typos.
(三)Versioning Tools
为了控制每个Sqoop工具的操作,可以使用Hadoop通用参数和工具限定符参数。 例如,对于导入工具,请查看帮助信息,这将输出当前Sqoop版本、git提交和构建信息到控制台::
To control the operation of each Sqoop tool, you can use Hadoop generic parameters and tool qualifier parameters.For example, for the import tool, check out the help information:
sql
sqoop version
sqoop-version
(四)Listing database tools
sqoop -list-databases实用程序列出给定数据库中的数据库,**它是检查Sqoop与特定数据库服务器的连接是否成功的方便工具。**为了建立到数据库的连接,您需要在使用list-databases工具时指定这些参数。
sqoop-list-databases工具用于列出给定数据库中可用的数据库。该工具可以方便地检查Sqoop与数据库服务器之间的连接是否成功。由于需要指定要连接的数据库的jdbc-uri,以及用于建立数据库连接的用户名和密码,因此在使用list-databases工具时需要指定这些参数。用法:
The sqoop-list-databases tool is used to list which databases are available in a given database. This tool makes it easy to check whether the connection between Sqoop and a database server is successful. Since you need to specify the jdbc-uri of the database you are connecting to, as well as the username and password you need to use to establish a connection to the database, you need to specify these parameters when using the list-databases tool. Usage:
sql
sqoop list-databases [General parameters] [Tool parameters]
1.Common tool parameters
| 参数(Parameter) | 中文描述 | 英文重点/考点提示 |
|---|---|---|
--connect <jdbc-uri> |
指定JDBC连接字符串 - 这是最核心的参数,必须准确配置数据库地址、端口和数据库名 | 必考 :格式为jdbc:数据库类型://主机:端口/数据库名,如jdbc:mysql://localhost:3306/testdb |
--connection-manager <class-name> |
指定连接管理器类 - 用于自定义数据库连接管理 | 考点:高级用法,通常使用默认管理器,考试可能考察异常情况处理 |
--driver <class-name> |
手动指定JDBC驱动类 - 当Sqoop无法自动加载驱动时使用 | 考点 :com.mysql.jdbc.Driver(MySQL 5.x)或com.mysql.cj.jdbc.Driver(MySQL 8.x) |
--hadoop-mapred-home <dir> |
覆盖HADOOP_MAPRED_HOME环境变量 - 指定Hadoop MapReduce的安装目录 | 考点:环境变量配置问题,通常在sqoop-env.sh中设置 |
--help |
打印使用说明 - 查看命令帮助信息 | 基础:忘记参数时的快速帮助 |
--password-file <path> |
设置包含认证密码的文件路径 - 安全的方式提供密码,文件权限需设置为400 | 重点考点 :比--password更安全,文件可位于HDFS或本地,权限chmod 400 |
-P |
从控制台读取密码 - 交互式输入密码,不会显示在历史记录中 | 考点 :安全性与--password的比较,-P更安全但需要手动输入 |
--password <password> |
设置认证密码 - 不安全的方式,密码会暴露在命令行历史中 | 考点:安全风险,不推荐在生产环境使用 |
--username <username> |
设置认证用户名 - 连接数据库的用户名 | 基础 :必需参数之一,常与--password或-P配合使用 |
--verbose |
打印详细信息 - 输出更详细的运行日志,便于调试 | 考点:调试和错误排查时使用 |
--connection-param-file <filename> |
提供连接参数的可选属性文件 - 将连接参数存储在属性文件中 | 考点:批量作业或重复使用时简化命令 |
--relaxed-isolation |
设置连接事务隔离级别为"读未提交" - 提高数据传输速度,但可能读到未提交的数据 | 重点考点 :性能优化参数,牺牲一致性提高速度,需数据库支持 |
2.实例
在mysql服务器上列出所用的数据库
List database schemas available on a MySQL server:
Dart
sqoop list-databases --connect jdbc:mysql://localhost or mysql-server address/ --username name -P
Dart
sqoop list-databases --connect jdbc:mysql://database.example.com/
information_schema employees
3.认证参数
dart
# 方式1:最不安全(会出现在历史记录)
--username root --password 123456
# 方式2:交互式(较安全)
--username root -P
# 然后输入密码
# 方式3:最安全(推荐)
--username root --password-file /user/home/.password
# 文件内容只有密码,权限400
- 口诀:一连二认三优化
- 一连:
--connect连数据库 - 二认:用户名密码认证方式(安全选-P或文件)
- 三优化:
--relaxed-isolation提速度
4.模板
dart
# 标准安全连接模板(考试推荐写法)
sqoop import \
--connect jdbc:mysql://localhost:3306/testdb \
--username admin \
--password-file /user/admin/.mysqlpass \
--table employees \
--target-dir /user/hadoop/emp_data
# 带性能优化的模板
sqoop import \
--connect jdbc:mysql://localhost:3306/bigdata \
--username etl_user \
-P \
--table sales \
--target-dir /user/hadoop/sales_data \
--relaxed-isolation \
-m 8
(五)List all table tools
类似的sqoop-list-tables工具是用于列出指定数据库的所有表的工具。
The similar sqoop-list-tables tool is a tool used to list all tables for a specified database.
1.语法
sql
sqoop list-tables [generic-args] [list-tables-args]
sqoop-list-tables [generic-args] [list-tables-args]
2.区别(与list-databases)
列表表和列表数据库之间的区别在于,您需要在jdbc-uri之后指定数据库名称。 当使用PostgreSQL时,默认情况下只获取公共SCHEMA中的表。 对于自定义模式,使用-schema参数列出指定模式的表。
The difference between list-tables and list-databases is that you need to specify the database name after the jdbc-uri. When using PostgreSQL, only the tables in the public SCHEMA are fetched by default. For custom schemas, use the -schema argument to list the tables for the specified schema.
(六)Generic Hadoop options
1.arguments
| 参数(Argument) | 中文描述 | 英文重点/考点提示 |
|---|---|---|
-conf <configuration file> |
指定应用程序配置文件 - 使用自定义的Hadoop配置文件覆盖默认配置 | 重点考点 :用于指定非默认位置的core-site.xml、hdfs-site.xml等配置文件路径 |
-D <property=value> |
为给定属性设置值 - 动态设置Hadoop配置属性,优先级最高 | 必考考点 :-D参数格式,如-D mapreduce.job.reduces=4,用于覆盖配置文件中的属性 |
| `-fs <local | namenode:port>` | 指定NameNode - 设置HDFS文件系统的地址和端口 |
| `-jt <local | jobtracker:port>` | 指定JobTracker - 设置MapReduce作业跟踪器的地址和端口 |
-files <逗号分隔的文件列表> |
指定要复制到MapReduce集群的文件 - 将本地文件分发到各个任务节点 | 重点考点:用于分发小文件(如配置文件、字典文件),在Map/Reduce任务中可通过相对路径访问 |
-libjars <逗号分隔的JAR包列表> |
指定要包含在classpath中的JAR文件 - 将自定义JAR包添加到任务的类路径 | 必考考点 :当任务需要第三方库时使用,如MySQL JDBC驱动mysql-connector-java.jar |
-archives <逗号分隔的归档文件列表> |
指定要在计算节点上解压的归档文件 - 分发并自动解压ZIP、TAR等归档文件 | 考点 :用于分发大文件或目录,解压后可通过#符号引用,如-archives sample.zip#sample |
2.语法
sql
bin/hadoop command [genericOptions] [commandOptions]
3.注意事项
您必须在工具名称之后提供通用参数-conf、-D等,但在任何特定于工具的参数(例如------connect)之前。注意,一般的Hadoop参数前面有一个破折号(-),而特定工具的参数前面有两个破折号(------),除非它们是单个字符的参数,如- p。
You must supply the generic arguments -conf, -D, and so on after the tool name but before any tool-specific arguments (such as --connect). Note that generic Hadoop arguments are preceded by a single dash character (-), whereas tool-specific arguments start with two dashes (--), unless they are single character arguments such as -P.
-conf、-D、-fs和-jt参数控制配置和Hadoop服务器设置。
The -conf, -D, -fs and -jt arguments control the configuration and Hadoop server settings.
三、Sqoop import tool
介绍如何将关系数据库中的数据导入到Hadoop的HDFS文件系统中 。 导入工具将RDBMS中的单个表导入HDFS。 表中的每一行在HDFS中都被视为一条记录。 所有导入的记录都以文本形式存储在文本文件中,或者以二进制形式存储在Avro文件和Sequence文件中。
- sqoop import usage:
bash
sqoop import (generic-args) (import-args)
(一)数据库连接参数
1.语法
要从数据库导入表HDFS,必须指定数据库连接字符串。 数据库连接字符串需要传递给Sqoop命令-连接选项,连接字符串的方法类似于URL。 在数据库连接字符串中描述连接到服务器和数据库的名称,还可以指定服务器端口。 如:
To the table from the database import HDFS, must specify the database connection string. The database connection string need to pass to Sqoop command - connect option, the connection string method similar to the URL. Described in the database connection string to connect to the server and the database name, you can also specify the server port. Such as:
bash
sqoop import --connect jdbc:mysql://database.example.com/employees
2.注意事项
- You should use the full hostname or IP address of the database host that can be seen by all your remote nodes.你应该使用所有远程节点都能看到的数据库主机名或IP地址。
- 在访问数据库之前,您可能需要对数据库进行身份验证。可以使用------username向数据库提供用户名。You might need to authenticate against the database before you can access it. You can use the --username to supply a username to the database.
3.sqoop提供密码给数据库的方式
| 功能描述 | 命令示例 | 中文说明 | 考点/注意事项 |
|---|---|---|---|
| 明文密码连接 (测试/开发环境) | sqoop list-databases --connect jdbc:mysql://127.0.0.1:3306 --username root --password Root123! |
使用明文密码列出所有数据库 | 最高危安全风险:密码会出现在命令行历史、进程列表中,生产环境禁止使用 |
| 交互式密码输入 (半安全方式) | sqoop list-databases --connect jdbc:mysql://127.0.0.1:3306 --username root -P |
提示输入密码,密码不会显示在屏幕上 | 安全考点:密码不在命令行中显示,但需要手动输入,不适合自动化脚本 |
| 创建密码文件 (安全基础) | echo -n 'Root123!' > /tools/.mysql.password chmod 400 /tools/.mysql.password |
将密码保存到文件并设置权限 | 关键考点 :1. -n避免换行符 2. chmod 400设置只读权限 3. 文件权限必须为400或600 |
| 密码文件认证 (生产环境推荐) | sqoop list-databases --connect jdbc:mysql://127.0.0.1:3306 --username root --password-file file:///tools/.mysql.password |
从密码文件读取密码进行认证 | 重点考点 :1. file://表示本地文件 2. 支持HDFS路径:hdfs:///user/.password 3. 最安全的认证方式 |
(1)明文密码连接
bash
sqoop list-databases \
--connect jdbc:mysql://127.0.0.1:3306 \
--username root \
--password Root123! # 密码明文暴露!
- ❌ 密码会保存在Shell历史记录中(history命令可查看)
- ❌ 进程列表中可见(ps aux | grep sqoop)
- ❌ 其他用户通过ps命令可看到密码
(2)交互式密码输入
bash
sqoop list-databases \
--connect jdbc:mysql://127.0.0.1:3306 \
--username root \
-P # 大写P,然后提示输入密码
- ✅ 密码不会出现在命令行历史中
- ✅ 密码不在进程列表中显示
- ✅ 考试常考:-P是大写字母,不是-p
(3)密码文件认证
- 创建密码文件的方法:
bash
# 方法1:使用echo(注意-n参数)
echo -n 'YourPassword' > /path/to/password.file
chmod 400 /path/to/password.file
# 方法2:使用printf(推荐,避免换行问题)
printf 'YourPassword' > /path/to/password.file
chmod 400 /path/to/password.file
# 方法3:使用vi/vim创建
vim /path/to/password.file
# 输入密码,保存,然后设置权限
chmod 400 /path/to/password.file
- 使用命令操作的方法:
bash
# 本地文件系统
sqoop import \
--connect jdbc:mysql://db.example.com:3306/testdb \
--username etl_user \
--password-file file:///home/etl/.db_password \
--table customers
# HDFS文件系统
sqoop import \
--connect jdbc:mysql://db.example.com:3306/testdb \
--username etl_user \
--password-file hdfs:///user/etl/.db_password \
--table customers
(二)Select Import data
Sqoop通常从表中导入数据,使用------table参数选择要导入的表。例如,------table employees。此参数还可以标识数据库中的视图或其他类似表的实体。
Sqoop typically imports data from a table, use --table argument to select which table to import from. For example, --table employees. This argument can also identify a VIEW or other table-like entity in a database.
1.Import control arguments
- 导入控制参数汇总表
| 参数 | 中文描述 | 英文重点/考点提示 |
|---|---|---|
--append |
追加数据到HDFS现有数据集 - 不覆盖已有数据,将新数据追加到目标目录 | 考点 :与--delete-target-dir互斥,不能同时使用 |
--as-avrodatafile |
导入数据为Avro数据文件 - 二进制格式,支持Schema演化,适合跨语言数据交换 | 考点:Avro格式特点(紧凑、高效、支持Schema) |
--as-sequencefile |
导入数据为SequenceFile - Hadoop二进制格式,支持压缩和分片 | 考点:适用于需要MapReduce直接处理的二进制数据 |
--as-textfile (默认) |
导入数据为纯文本文件 - 默认格式,可读性好但性能较低 | 考点:默认格式,分隔符可自定义 |
--as-parquetfile |
导入数据为Parquet文件 - 列式存储格式,查询性能高,适合分析型负载 | 考点:列式存储优势(压缩率高、查询快) |
--boundary-query <statement> |
用于创建分片的边界查询 - 自定义查询获取数据的最小和最大值 | 高级考点 :当默认的MIN/MAX查询性能差时使用 |
--columns <col,col,col...> |
从表中选择要导入的列 - 指定要导入的字段列表 | 必考:列名用逗号分隔,控制导入的数据量 |
--delete-target-dir |
如果目标目录存在则删除 - 强制清空目标目录后重新导入 | 考点 :与--append互斥,确保数据一致性 |
--direct |
使用数据库的直接连接器 - 绕过JDBC,使用数据库原生工具(如mysqldump) | 重点考点:大幅提升性能,但仅部分数据库支持(MySQL、PostgreSQL) |
--fetch-size <n> |
一次从数据库读取的记录数 - 控制JDBC每次获取的数据量 | 性能考点:默认1000,增大可减少网络往返次数 |
--inline-lob-limit <n> |
设置内联LOB(大对象)的最大大小 - 超过此大小的LOB会单独存储 | 高级考点:处理BLOB/CLOB等大字段 |
-m,--num-mappers <n> |
使用n个Map任务并行导入 - 控制并行度 | 必考考点:默认4,影响性能和HDFS文件数 |
-e,--query <statement> |
导入查询语句的结果 - 使用自定义SQL查询导入数据 | 重点考点 :必须包含$CONDITIONS占位符,需指定--split-by |
--split-by <column-name> |
用于分割工作单元的列 - 当表无主键或主键分布不均时指定 | 重点考点:均匀分布的列,通常为整数或日期类型 |
--split-limit <n> |
每个分片大小的上限 - 仅适用于整数和日期列,日期以秒计算 | 高级考点:控制每个Map任务处理的数据范围 |
--autoreset-to-one-mapper |
如果表无主键且未指定split-by,则自动重置为1个Mapper | 考点 :与--split-by互斥,用于避免全表扫描 |
--table <table-name> |
要读取的表名 - 指定源数据表 | 必考 :与--query互斥,只能二选一 |
--target-dir <dir> |
HDFS目标目录 - 指定数据导入到HDFS的路径 | 必考 :目录不能已存在(除非使用--append或--delete-target-dir) |
--temporary-rootdir <dir> |
导入过程中临时文件的HDFS目录 - 覆盖默认的"_sqoop"目录 | 高级考点:临时文件存放位置,导入完成后自动清理 |
--warehouse-dir <dir> |
表目标目录的HDFS父目录 - 为每个表创建子目录 | 考点 :与--target-dir互斥,用于批量导入多个表 |
--where <where clause> |
导入时使用的WHERE子句 - 过滤要导入的数据行 | 考点 :SQL WHERE条件,如--where "id>100 AND status='active'" |
-z,--compress |
启用压缩 - 减少存储空间和网络传输量 | 性能考点:默认使用gzip压缩 |
--compression-codec <c> |
使用Hadoop编解码器 - 指定压缩算法(默认gzip) | 考点:常用编解码器:gzip、snappy、lzo、bzip2 |
--null-string <null-string> |
字符串列空值的写入字符串 - 指定如何表示字符串NULL值 | 考点 :默认"null",可设为空字符串""或\N |
--null-non-string <null-string> |
非字符串列空值的写入字符串 - 指定如何表示非字符串NULL值 | 考点 :默认"null",需与--null-string区分 |
2. 高频考点分类
(1)性能优化类参数(考试重点)
| 参数 | 作用 | 典型值/用法 |
|---|---|---|
--direct |
使用数据库原生工具加速 | MySQL: mysqldump |
-m,--num-mappers |
控制并行度 | 根据数据量和集群资源设置(4-16) |
--fetch-size |
减少JDBC网络往返 | 1000-10000(根据行大小调整) |
-z,--compress |
压缩输出数据 | 配合--compression-codec snappy |
--split-by |
均匀分割数据 | 选择均匀分布的整数列(如ID) |
(2) 数据选择类参数(必考)
| 参数 | 作用 | 使用场景 |
|---|---|---|
--table vs --query |
全表导入 vs 自定义查询 | 简单导入用--table,复杂过滤用--query |
--columns |
选择特定列 | 减少数据传输量:--columns "id,name,age" |
--where |
行级过滤 | 条件筛选:--where "salary>5000 AND dept='IT'" |
(3)文件格式类参数(理解差异)
| 格式 | 特点 | 适用场景 |
|---|---|---|
--as-textfile |
文本,可读性好 | 默认,需要查看文件内容时 |
--as-sequencefile |
二进制,可分片 | MapReduce直接处理 |
--as-avrodatafile |
二进制,Schema支持 | 跨语言数据交换,Schema演化 |
--as-parquetfile |
列式存储,查询快 | 分析型查询,Hive/Spark分析 |
4. 空值处理参数(易错点)
------null-string和------null-non-string参数是可选的。如果没有指定,则使用字符串"null"。
The --null-string and --null-non-string arguments are optional. If not specified, then the string "null" will be used.
bash
#正确处理NULL值
sqoop import \
--null-string '\\N' \
--null-non-string '\\N' \
...其他参数
#Hive兼容的NULL处理
sqoop import \
--null-string '\\\\N' \ # 两个反斜杠,实际表示\N
--null-non-string '\\\\N'
3.基本导入
bash
#导入整个表,使用4个Mapper,文本格式
sqoop import \
--connect jdbc:mysql://localhost:3306/testdb \
--username root \
--password-file file:///home/.password \
--table employees \
--target-dir /user/hadoop/employees \
-m 4 \
--as-textfile \
--fields-terminated-by ','
4.选择性导入
bash
# 只导入部分列和行,使用WHERE条件
sqoop import \
--connect jdbc:mysql://localhost:3306/testdb \
--table sales \
--columns "order_id,customer_id,amount,sale_date" \
--where "sale_date >= '2023-01-01' AND amount > 1000" \
--target-dir /user/hadoop/sales_2023_large \
-m 8 \
--direct \
--compress
5.Free-form Query Imports
(1)说明
-
Sqoop还可以导入任意SQL查询的结果集 。你可以使用
------query参数指定一条SQL语句,使用------table、------columns和------where参数实现的是选择性导入。 -
Sqoop can also import the result set of an arbitrary SQL query. Instead of using the --table, --columns and --where arguments, you can specify a SQL statement with the --query argument.
-
在导入自由格式查询时,必须使用------
target-dir指定目标目录。 -
When importing a free-form query, you must specify a destination directory with --target-dir.
-
如果想并行导入一个查询的结果,那么每个map任务都需要执行一个查询的副本 ,并根据Sqoop推断的边界条件对结果进行分区。你的查询必须包含令牌$CONDITIONS,每个Sqoop进程都会用唯一的条件表达式替换它。你还必须使用------split-by选择一个分割列。
-
If you want to import the results of a query in parallel, then each map task will need to execute a copy of the query, with results partitioned by bounding conditions inferred by Sqoop. Your query must include the token $CONDITIONS which each Sqoop process will replace with a unique condition expression. You must also select a splitting column with --split-by.
(2)实例
bash
# 使用自定义查询,必须包含$CONDITIONS
sqoop import \
--connect jdbc:mysql://localhost:3306/testdb \
--query 'SELECT e.*, d.dept_name FROM employees e JOIN departments d ON e.dept_id = d.dept_id WHERE $CONDITIONS' \
--split-by e.employee_id \
--target-dir /user/hadoop/emp_with_dept \
-m 4
(三)Controlling Parallelism
**默认的导入通道使用JDBC连接。 有些数据库可以提供性能更高的直接导入,**比如MySQL提供的mysqldump工具,可以快速的将MySQL中的数据转移到其他系统中。 通过使用- direct参数,告诉Sqoop应该尝试使用直接导入通道,它可能比使用默认的JDBC方式导入更快。
-
Sqoop imports data in parallel from most database sources.Sqoop从大多数数据库源并行导入数据。
-
You can specify the number of map tasks (parallel processes) to use to perform the import by using the -m or --num-mappers argument.用户可以使用
-m或------num-mappers参数指定执行导入时使用的map任务(并行进程)数量。 -
By default, four tasks are used. Some databases may see improved performance by increasing this value to 8 or 16.默认使用4个任务。在某些数据库中,将该值增加到8或16可以提高性能。
-
When performing parallel imports, Sqoop will identify the primary key column (if present) in a table and use it as the splitting column.在执行并行导入时,Sqoop将识别表中的主键列(如果存在的话),并将其用作拆分列。
-
The low and high values for the splitting column are retrieved from the database, and the map tasks operate on evenly-sized components of the total range.拆分列的低值和高值从数据库中检索,map任务在总范围的平均大小的组件上操作。
-
If the actual values for the primary key are not uniformly distributed across its range, then this can result in unbalanced tasks.如果主键的实际值在其范围内不均匀分布,则会导致任务不平衡。
-
You should explicitly choose a different column with the --split-by argument.你应该使用------split-by参数明确地选择一个不同的列。
-
If a table does not have a primary key defined and the --split-by is not provided, then import will fail unless the number of mappers is explicitly set to one with the --num-mappers 1 option or the --autoreset-to-one-mapper option is used. 如果一个表没有定义主键,并且没有提供------split-by ,那么导入将会失败,除非使用------num-mappers 1选项明确地将mapper的数量设置为1,或者使用------autoreset-to-one-mapper选项。
-
The option --autoreset-to-one-mapper is typically used with the import-all-tables tool to automatically handle tables without a primary key in a schema.
------autoreset-to-one-mapper通常与import-all-tables工具一起使用,以自动处理模式中没有主键的表。 -
--target-dir is incompatible with --warehouse-dir.------target-dir与------warehouse-dir不兼容。
-
When using direct mode, you can specify additional arguments which should be passed to the underlying tool.当使用直接模式时,您可以指定额外的参数,这些参数应该传递给底层工具。
-
By default, imports go to a new target location. If the destination directory already exists in HDFS, Sqoop will refuse to import and overwrite that directory's contents.默认情况下,导入会转到新的目标位置。如果目标目录已经存在于HDFS中,Sqoop将拒绝导入并覆盖该目录的内容。
-
If you use the --append argument, Sqoop will import data to a temporary directory and then rename the files into the normal target directory in a manner that does not conflict with existing filenames in that directory.如果使用------append参数,Sqoop会将数据导入到一个临时目录中,然后将文件重命名到普通的目标目录中,这种方式不会与该目录中现有的文件名冲突。
(四)Incremental imports
Sqoop提供增量导入模式,可以跳过旧记录等已导入的记录,只导入新记录。 对于周期性批量分析,往往之前不需要导入数据,只需要导入新的数据,在这种情况下非常适合采用增量导入的方式,因为之前的数据不需要重复导入可以大大提高导入的速度。
Sqoop provides incremental import mode, you can skip the old records such as records have been imported, only import the new record. For periodic batch analysis, often before there is no need to import data, only the import ofnew data, in this case is very suitable for using incremental import way, because ofprevious data do not need to repeat the import can greatly improve the speed of import.
1.参数
| 参数 | 中文描述 | 英文重点/考点提示 |
|---|---|---|
--check-column <col> |
指定用于检查增量数据的列 - 用于确定哪些行是新数据需要导入 | 必考考点 :列类型不能是字符类型(CHAR/NCHAR/VARCHAR/VARNCHAR/LONGVARCHAR/LONGNVARCHAR),必须是整数或时间戳类型 |
--incremental <mode> |
指定Sqoop确定新数据行的方式 - 定义增量导入的模式 | 重点考点 :两种模式:append(追加,基于递增ID)和lastmodified(最后修改,基于时间戳) |
--last-value <value> |
指定检查列的上次导入最大值 - 仅导入检查列值大于此值的行 | 必考考点:格式必须与检查列类型匹配,整数列给整数,时间戳列给时间戳 |
2.核心参数
(1) --check-column
bash
# ✅ 正确的检查列类型(考试重点)
--check-column id # 整数列,用于append模式
--check-column last_updated # 时间戳列,用于lastmodified模式
- 允许的数据类型:
- 整数类型:INT, BIGINT, INTEGER等
- 日期/时间类型:DATE, TIMESTAMP, DATETIME等
(2) --last-value
在增量导入结束时,应该指定为------last-value的值将打印到屏幕上,以便后续导入使用 。在运行后续导入时,应该以这种方式指定------last-value,以确保只导入新的或更新的数据。这可以通过创建增量导入作为保存的作业来自动处理,这是执行重复增量导入的首选机制。
At the end of an incremental import, the value which should be specified as --last-value for a subsequent import is printed to the screen. When running a subsequent import, you should specify --last-value in this way to ensure you import only the new or updated data. This is handled automatically by creating an incremental import as a saved job, which is the preferred mechanism for performing a recurring incremental import.
bash
# 整数列示例(append模式)
--last-value 1000
# 导入ID > 1000的记录
# 时间戳示例(lastmodified模式)
--last-value "2023-12-31 23:59:59"
--last-value "2023-12-31"
# 导入时间戳 > 指定时间的记录
3.--incremental (模式选择)
Sqoop支持两种增量导入模式:append模式和lastmodified模式。 您可以使用- incremental参数来指定使用哪种模型
| 模式 | 检查列类型 | 使用场景 | 处理方式 |
|---|---|---|---|
append |
整数列 | 只新增不更新的表(如:日志表) | 只导入新行,不更新已有行 |
lastmodified |
时间戳列 | 会更新已有记录的表 | 导入新行和更新行 |
bash
# 模式1:append(追加模式)
--incremental append
# 适用场景:基于单调递增ID的新增数据(如自增主键)
# 特点:只导入ID大于last-value的新行
# 模式2:lastmodified(最后修改模式)
--incremental lastmodified
# 适用场景:基于时间戳的更新和新增数据
# 特点:导入时间戳大于last-value的新行和更新行
(1)append
当导入一个表时,如果新行不断增加,行id值不断增加,则应该指定追加模式。使用------check-column指定包含行id的列。Sqoop导入check列的值大于------last-value指定值的行。
You should specify append mode when importing a table where new rows are continually being added with increasing row id values. You specify the column containing the row's id with --check-column. Sqoop imports rows where the check column has a value greater than the one specified with --last-value.
(2)lastmodified
Sqoop支持的另一种表更新策略称为lastmodified模式。当源表中的行可能会更新,并且每次更新都会将"last-modified"列的值设置为当前时间戳时,用户应该使用该选项。如果check列的时间戳比------last-value指定的时间戳更新,则导入。
An alternate table update strategy supported by Sqoop is called lastmodified mode. You should use this when rows of the source table may be updated, and each such update will set the value of a last-modified column to the current timestamp. Rows where the check column holds a timestamp more recent than the timestamp specified with --last-value are imported.
4.示例
(1)append模式增量导入
bash
# 基于ID的增量导入(常见用例)
sqoop import \
--connect jdbc:mysql://localhost:3306/testdb \
--username root \
--password-file file:///home/.password \
--table orders \
--target-dir /user/hadoop/orders \
--incremental append \
--check-column order_id \ # 必须是整数列
--last-value 5000 \ # 上次导入的最大order_id
-m 4
(2)lastmodified模式增量导入
bash
#基于时间戳的增量导入(处理数据更新)
sqoop import \
--connect jdbc:mysql://localhost:3306/testdb \
--table customers \
--target-dir /user/hadoop/customers \
--incremental lastmodified \
--check-column update_time \ # 必须是时间戳列
--last-value "2024-01-01 00:00:00" \ # 上次导入的最大时间戳
--merge-key customer_id \ # 合并时使用的主键
-m 4
5.口诀
增量导入三要素,检查列、模式、最后值
检查列:整数时间戳,字符类型不能用
模式:append只新增,lastmodified管更新
最后值:类型要匹配,上次断点要记牢
合并数据用merge,主键相同好合并
(五)Import file format of choice
1.file format to import
您可以选择两种导入格式:分隔文本或SequenceFile。
File Formats Selection to Import: - You can import data in one of two file formats: delimited text or SequenceFiles.
带分隔符的文本是要导入的默认格式 ,也可以使用- as - textfile参数显式指定。 此参数将把每条记录以字符串的形式写入输出文件,在每列和行之间使用分隔符。 这些分隔符可以是逗号、制表符或其他字符。 (可以显示指定的分隔符,
Delimited text is the default import format. You can also specify it explicitly by using the --as-textfile argument. This argument will write string-based representations of each record to the output files, with delimiter characters between individual columns and rows. These delimiters may be commas, tabs, or other characters. (The delimiters can be selected; see "Output line formatting arguments.")
2.控制参数
| 参数 | 中文描述 | 英文重点/考点提示 |
|---|---|---|
--fields-terminated-by <char> |
设置字段分隔符 - 指定列与列之间的分隔字符 | 必考考点 :默认是逗号(,),考试常考其他分隔符如制表符(\t)、竖线(` |
--lines-terminated-by <char> |
设置行结束符 - 指定记录之间的分隔字符 | 考点 :默认是换行符(\n),Windows系统可能是\r\n |
--enclosed-by <char> |
设置字段包围字符 - 用指定字符包围每个字段(强制) | 考点 :如双引号("),字段会被强制包围,即使字段内没有特殊字符 |
--optionally-enclosed-by <char> |
设置字段可选包围字符 - 只在字段包含分隔符时才包围 | 重点考点 :与--enclosed-by的区别,智能包围,节省空间 |
--escaped-by <char> |
设置转义字符 - 用于转义字段中的特殊字符 | 考点 :默认没有转义字符,常用反斜杠(\) |
--mysql-delimiters |
使用MySQL默认分隔符集 - 快速设置MySQL兼容格式 | 重点考点 :相当于--fields-terminated-by , --lines-terminated-by \n --escaped-by \\ --optionally-enclosed-by ' |
3.特殊的转义字符
| 转义字符 | 中文描述 | 实际字符 | 用途与考点提示 |
|---|---|---|---|
\b |
退格符 - 将光标向左移动一个位置 | Backspace | 考点:较少使用,主要用于特殊格式要求的数据处理 |
\n |
换行符 - 新的一行 | Newline (Line Feed) | 必考考点:默认的行结束符,Unix/Linux系统标准换行符 |
\r |
回车符 - 将光标移动到行首 | Carriage Return | 重点考点 :Windows系统换行符的一部分(与\n组合为\r\n) |
\t |
制表符 - 水平制表符 | Tab | 必考考点:常用于TSV(Tab-Separated Values)格式,替代逗号作为字段分隔符 |
\" |
双引号 - 字面双引号字符 | Double Quote | 重点考点:用于在字段包围中使用双引号,避免与包围字符冲突 |
\' |
单引号 - 字面单引号字符 | Single Quote | 考点:用于在字段包围中使用单引号,MySQL常用单引号包围 |
\\ |
反斜杠 - 字面反斜杠字符 | Backslash | 必考考点:转义字符本身,用于在数据中表示反斜杠 |
\0 |
空字符 - NULL字符,ASCII码0 | NUL (Null character) | 重点考点:特殊用途:1. 在字段/行之间插入NULL字符 2. 禁用包围/转义功能 |
4.The default delimiters
-
a comma (,) for fields,
-
a newline (\n) for records,
-
no quote character, and
-
no escape character.
-
------mysql-delimiter参数是一个简写参数,它使用mysqldump程序的默认分隔符。如果您结合使用mysqldump分隔符和直接模式导入(使用------direct),可以实现非常快速的导入。 -
The --mysql-delimiters argument is a shorthand argument which uses the default delimiters for the mysqldump program. If you use the mysqldump delimiters in conjunction with a direct-mode import (with --direct), very fast imports can be achieved.
-
虽然分隔符的选择对于文本模式导入来说是最重要的,但如果你使用------
as-sequencefile导入到sequencefile,它仍然是重要的。生成的类```toString()``方法将使用你指定的分隔符,因此后续格式化输出数据将依赖于你选择的分隔符。 -
While the choice of delimiters is most important for a text-mode import, it is still relevant if you import to SequenceFiles with --as-sequencefile. The generated class' toString() method will use the delimiters you specify, so subsequent formatting of the output data will rely on the delimiters you choose.
5.Input analytical parameters
| 参数 | 中文描述 | 英文重点/考点提示 |
|---|---|---|
--input-enclosed-by <char> |
强制字段包围符号 - 指定输入数据中包围字段的字符,必须精确匹配 | 重点考点:输入数据必须严格使用指定字符包围字段,否则解析失败 |
--input-fields-terminated-by <char> |
输入字段分隔符 - 指定输入数据中字段之间的分隔字符 | 必考考点 :必须与输入数据的实际分隔符完全一致,默认逗号(,) |
--input-lines-terminated-by <char> |
输入行结束符 - 指定输入数据中记录之间的结束字符 | 考点 :必须匹配输入数据的行结束符,默认换行符(\n) |
--input-optionally-enclosed-by <char> |
可选字段包围符号 - 指定输入数据中可选包围字段的字符 | 重点考点:输入数据中可能有的字段被包围,有的没有,使用此参数智能解析 |
bash
# 输出参数:控制如何写入HDFS
--fields-terminated-by ',' # 输出时用逗号分隔
--enclosed-by '"' # 输出时用双引号包围
# 输入参数:控制如何读取HDFS数据(导出时)
--input-fields-terminated-by ',' # 读取时按逗号分隔
--input-enclosed-by '"' # 读取时识别双引号包围
6.其他数据文件格式
- 当Sqoop将数据导入HDFS时,它会生成一个Java类 ,这个类可以重新解释它导入带分隔符格式的文本文件时创建的文本文件。分隔符可以通过参数来选择,例如------fields-terminated-by;这控制了数据如何写入磁盘,以及生成的parse()方法如何重新解释这些数据。parse()方法使用的定界符可以独立于输出参数选择,可以使用------input-fields-terminated-by,等等。
- When Sqoop imports data to HDFS, it generates a Java class which can reinterpret the text files that it creates when doing a delimited-format import. The delimiters are chosen with arguments such as --fields-terminated-by; this controls both how the data is written to disk, and how the generated parse() method reinterprets this data. The delimiters used by the parse() method can be chosen independently of the output arguments, by using --input-fields-terminated-by, and so on.
- sequencefile是一种二进制格式,以自定义的特定于记录的数据类型存储单个记录。这些数据类型表现为Java类。 Sqoop会自动生成这些数据类型。这种格式支持以二进制形式精确存储所有数据,适合存储二进制数据(例如VARBINARY列),或者需要自定义MapReduce程序操作的数据(从sequencefile读取数据比从文本文件读取性能更高,因为不需要解析记录)。
- SequenceFiles are a binary format that store individual records in custom record-specific data types. These data types are manifested as Java classes. Sqoop will automatically generate these data types for you. This format supports exact storage of all data in binary representations, and is appropriate for storing binary data (for example, VARBINARY columns), or data that will be principle manipulated by custom MapReduce programs (reading from SequenceFiles is higher-performance than reading from text files, as records do not need to be parsed).
- Avro数据文件是一种紧凑、高效的二进制格式,可以与用其他编程语言编写的应用程序互操作。Avro还支持版本控制, 例如,在表中添加或删除列时,可以同时处理之前导入的数据文件和新的数据文件。
- Avro data files are a compact, efficient binary format that provides interoperability with applications written in other programming languages. Avro also supports versioning, so that when, e.g., columns are added or removed from a table, previously imported data files can be processed along with new ones.
- 默认情况下,数据不压缩。 你可以使用
deflate (gzip)算法和-z或------compress参数来压缩数据,或者使用------compression-codec参数指定任何Hadoop压缩编解码器。这适用于SequenceFile、text和Avro文件。 - By default, data is not compressed. You can compress your data by using the deflate (gzip) algorithm with the -z or --compress argument, or specify any Hadoop compression codec using the --compression-codec argument. This applies to SequenceFile, text, and Avro files.
(六)Importing Data into Hive
Sqoop的导入工具的主要功能是将数据上传到HDFS文件中。如果你的HDFS集群关联了一个Hive元数据存储 ,那么Sqoop也可以通过生成并执行CREATE TABLE语句来定义数据在Hive中的布局,从而将数据导入Hive。将数据导入Hive很简单,只需在Sqoop命令行中添加------Hive -import选项。
Sqoop's import tool's main function is to upload your data into files in HDFS. If you have a Hive metastore associated with your HDFS cluster, Sqoop can also import the data into Hive by generating and executing a CREATE TABLE statement to define the data's layout in Hive. Importing data into Hive is as simple as adding the --hive-import option to your Sqoop command line.
如果Hive表已经存在,可以指定------Hive -overwrite选项,表示必须替换Hive中已经存在的表。数据导入到HDFS或者省略这一步后,Sqoop会生成一个Hive脚本,其中包含使用Hive的类型定义列的CREATE TABLE操作,以及LOAD data INPATH语句,将数据文件移动到Hive的仓库目录中。
If the Hive table already exists, you can specify the --hive-overwrite option to indicate that existing table in hive must be replaced. After your data is imported into HDFS or this step is omitted, Sqoop will generate a Hive script containing a CREATE TABLE operation defining your columns using Hive's types, and a LOAD DATA INPATH statement to move the data files into Hive's warehouse directory.
1.导入参数
| 参数 | 中文描述 | 英文重点/考点提示 |
|---|---|---|
--hive-home <dir> |
覆盖HIVE_HOME环境变量 - 指定Hive安装目录 | 考点:当Hive未在标准路径或需要指定特定版本时使用 |
--hive-import |
导入表到Hive - 启用Hive导入功能,自动创建Hive表并加载数据 | 必考考点 :如果不设置分隔符,将使用Hive默认分隔符(\001) |
--hive-overwrite |
覆盖Hive表中现有数据 - 删除Hive表中现有数据,然后导入新数据 | 重点考点:如果不指定此参数,当Hive表已存在时,导入会失败 |
--create-hive-table |
如果设置,目标Hive表存在则作业失败 - 默认false,即表存在时不创建也不失败 | 考点:用于确保不覆盖现有表结构,默认行为是表存在时跳过创建步骤 |
--hive-table <table-name> |
设置导入到Hive时使用的表名 - 可以包含数据库名(如dbname.tablename) |
必考考点 :格式为[数据库名.]表名,默认在default数据库创建 |
--hive-drop-import-delims |
导入到Hive时从字符串字段中删除\n、\r和\01 - 防止Hive将这些字符误认为分隔符 |
重点考点:处理文本字段中的换行符和分隔符,避免Hive解析错误 |
--hive-delims-replacement |
用用户定义的字符串替换字符串字段中的\n、\r和\01 |
考点:比drop更灵活,保留数据但替换特殊字符 |
--hive-partition-key |
Hive分区字段名 - 指定用于分区的字段 | 重点考点 :与--hive-partition-value配合使用,创建分区表 |
--hive-partition-value <v> |
分区键值 - 为本次导入指定分区键的具体值 | 必考考点 :必须与--hive-partition-key同时使用,值必须是字符串 |
--map-column-hive <map> |
覆盖SQL类型到Hive类型的默认映射 - 为指定列自定义Hive数据类型 | 高级考点 :使用URL编码处理逗号等特殊字符,如DECIMAL(1%2C%201)表示DECIMAL(1, 1) |
2.基础导入流程
bash
sqoop import \
--connect jdbc:mysql://localhost:3306/testdb \
--table employees \
--hive-import \ # 启用Hive导入
--hive-table employees_hive \ # Hive表名
--hive-overwrite \ # 覆盖现有数据
-m 1
3.分隔符处理
bash
# 如果不指定分隔符,使用Hive默认分隔符
--hive-import # 自动使用Hive默认分隔符:\001
# 手动指定分隔符(覆盖默认)
sqoop import \
--hive-import \
--fields-terminated-by ',' \ # 指定逗号分隔
--lines-terminated-by '\n' \
...
# Hive默认分隔符(必须记住)
字段分隔符: \001 (Ctrl+A)
集合元素分隔符: \002 (Ctrl+B)
Map键值分隔符: \003 (Ctrl+C)
行分隔符: \n
4.特殊字符处理
bash
# 方法1:直接删除特殊字符(可能丢失数据)
--hive-drop-import-delims
# 效果:将字段中的\n, \r, \01替换为空
# 方法2:替换特殊字符(保留数据完整性)
--hive-delims-replacement " "
# 效果:将字段中的\n, \r, \01替换为空格
# 方法3:使用自定义分隔符(避免冲突)
--fields-terminated-by '\t' # 使用制表符,避免与数据中的逗号冲突
5.分区表导入
bash
# 创建分区表并导入数据
sqoop import \
--connect jdbc:mysql://localhost:3306/testdb \
--table sales \
--hive-import \
--hive-table sales_partitioned \
--hive-partition-key sale_date \ # 分区字段
--hive-partition-value "2023-12" \ # 分区值
--hive-overwrite
(七)Importing Data into HBase
通过指定- hbase - table,可以指示在表中指定导入hbase的Sqoop数据。 首先读取每一行的输入表,将其转换为Hbase,将数据放入Hbase表。 默认情况下,Sqoop将分别使用open作为HBase的行键列。 如果没有分别指定一个键列,Sqoop将尝试识别源表的主键列,如果HBase表中只存在一个键列。 也可以使用- hbase - row -键行选项手动指定键列。 每个输出列将放置在相同的列族中,必须指定列族名称才能使用列族。
1.导入参数
| 参数 | 中文描述 | 英文重点/考点提示 |
|---|---|---|
--column-family <family> |
设置导入的目标列族 - 指定HBase表中的列族名称 | 必考考点 :必须指定列族,所有导入的列都将放在这个列族下,格式如:cf 或 info |
--hbase-create-table |
如果目标HBase表不存在则自动创建 - 允许在导入时自动创建HBase表 | 重点考点:如果不指定此参数且表不存在,导入将失败 |
--hbase-row-key <col> |
指定哪一列用作Row Key - 选择输入表中的列作为HBase的行键,复合键用逗号分隔 | 必考考点:Row Key是HBase表设计的关键,必须指定且唯一 |
--hbase-table <table-name> |
指定要导入的HBase表名 - 目标HBase表的名称 | 必考考点 :必须指定HBase表名,格式如 namespace:table 或 table |
--hbase-bulkload |
启用批量加载模式 - 使用HBase的BulkLoad功能,避免写入压力 | 高级考点:大数据量导入时使用,生成HFile直接加载到HBase |
2.导入流程
bash
sqoop import \
--connect jdbc:mysql://localhost:3306/testdb \
--table users \
--hbase-table users_hbase \ # HBase表名
--column-family info \ # 列族名
--hbase-row-key id \ # 使用id列作为Row Key
--hbase-create-table \ # 表不存在则创建
-m 1
3.核心参数
bash
# HBase导入的四个必须/核心参数
--hbase-table <name> # 指定HBase表名
--column-family <name> # 指定列族
--hbase-row-key <col> # 指定Row Key列
# 如果表不存在,还需要:
--hbase-create-table # 自动创建表
4.口诀
HBase导入四件套,表名列族行键不能少
hbase-table定表名,column-family设列族
hbase-row-key是关键,单列复合要分清
表不存在不用慌,hbase-create-table来帮忙
大数据量要优化,hbase-bulkload批量加载
HBase设计要合理,Row Key散列避热点
(八)Import Results Validation
导入命令执行完成后在控制台上显示的物品导入记录号不一定为真。 要验证导入的结果,可以使用- validation选项。
Import command execution is completed on the console display article import record number is not necessarily true. To validate the result of the import, you can use - validation option.
1.Validate parameter
| 参数 | 中文描述 | 英文重点/考点提示 |
|---|---|---|
--validate |
启用数据复制验证 - 在数据导入/导出后进行数据验证,确保数据一致性 | 必考考点:仅支持单表复制验证,不支持多表或复杂查询 |
--validator <class-name> |
指定验证器类 - 使用自定义的验证器实现数据验证逻辑 | 高级考点 :默认使用RowCountValidator,可自定义扩展 |
--validation-threshold <class-name> |
指定验证阈值类 - 定义验证结果的容错阈值标准 | 重点考点 :默认使用AbsoluteValidationThreshold,要求源和目标记录数完全相等 |
--validation-failurehandler <class-name> |
指定验证失败处理器类 - 定义验证失败时的处理方式 | 考点 :默认使用LogOnFailureHandler,仅记录警告信息 |
2.basic interface
(1)ValidationThreshold
确定源和目标之间的误差范围是否可接受:绝对误差、百分比容错等。默认实现是AbsoluteValidationThreshold,它确保来自源和目标的行计数相同。
Determines if the error margin between the source and target are acceptable: Absolute, Percentage Tolerant, etc. Default implementation is AbsoluteValidationThreshold which ensures the row counts from source and targets are the same.
(2)ValidationFailureHandler
记录错误/警告、中止等 。默认实现是LogOnFailureHandler,它将警告消息记录到配置的记录器中。
Responsible for handling failures: log an error/warning, abort, etc. Default implementation is LogOnFailureHandler that logs a warning message to the configured logger.
(3)Validator
通过将决策委托给ValidationThreshold并将失败处理委托给ValidationFailureHandler来驱动验证逻辑。默认实现是RowCountValidator,它从源和目标验证行计数。
Drives the validation logic by delegating the decision to ValidationThreshold and delegating failure handling to ValidationFailureHandler. The default implementation is RowCountValidator which validates the row counts from source and the target.
- 验证器:RowCountValidator - 只验证行数
- 阈值:AbsoluteValidationThreshold - 必须完全相等
- 失败处理:LogOnFailureHandler - 仅记录日志,不停止作业
3.验证过程
- 执行数据转移操作
- 分别统计源端和目标端的记录数
- 比较两者是否一致
- 根据验证阈值判断是否通过
4.基本数据验证
bash
# 导入数据并验证记录数
sqoop import \
--connect jdbc:mysql://localhost:3306/testdb \
--table employees \
--target-dir /user/hadoop/employees \
--validate \ # 启用验证
-m 1
# 导出数据并验证记录数
sqoop export \
--connect jdbc:mysql://localhost:3306/testdb \
--table employees_export \
--export-dir /user/hadoop/emp_data \
--validate \ # 启用验证
-m 1
(九)The import performance optimization
1. Map 任务数量设置
Sqoop的import任务默认使用4个Map任务,这并不总是最好的选择。Map任务数量可以通过-m或------num-mappers选项指定 ,可以有以下几种方式。
Sqoop import tasks use 4 Map tasks by default, which is not always the best choice. Map task number can be specified by -m or --num-mappers option, which can be considered as the following ways:
(1)数据量小的情况
当数据量小于HDFS中定义的数据块大小时,只需使用一个Map任务,可以有效地减少MapReduce任务的执行时间,减少生成的文件数量,节省磁盘空间。
When the amount of data is smaller than the Block Size defined in HDFS, only one Map task should be used, which can effectively reduce the execution time of MapReduce tasks, as well as reduce the number of generated files and save disk space.
(2)数据量大的情况
当数据量很大时,可以通过增加并行度来提高性能, 但增加并行度并不一定会让性能变得更好。通常情况下,并行度不应该超过该节点上的一个MapReduce任务可以从YARN请求的最大虚拟cpu数(对应的配置项是YARN .scheduler。Maximum-allocation-vcores,可以在yarn-site.xml中配置,默认值为4)。
When the amount of data is large, performance can be improved by increasing the parallelism, but it is not always getting better to increase it. Normally the parallelism should not exceed the maximum number of virtual CPUs that can be requested from YARN for a MapReduce task on that node (the corresponding configuration item is yarn.scheduler.maximum-allocation-vcores, which can be configured in yarn-site.xml with a default value of 4).
2.fetch size
你可以使用------fetch-size来指定执行导入时一次从数据库中读取数据的最大数量,默认值是1000。建议考虑以下几个方面。
You can use --fetch-size to specify the maximum number of data to be read from the database at a time when executing the import, the default value is 1000. It is recommended to consider the following aspects.
- a.要导入的表是一个宽表,它是否包含大对象字段还是长文本字段。Whether the table to be imported is a wide table, and whether it contains large object fields or long text fields.
- b.Database性能
Database Performance
3.--direct mode
如果数据库支持------direct模式,有时使用它导入可以提高性能。此外,使用------relax -isolation选项指示Sqoop使用read uncommitted隔离级别导入数据,可以在数据库支持的情况下提高数据传输速度。
Using --direct mode to import sometimes can improve performance if the database supports it. Also, using the --relaxed-isolation option to instruct Sqoop to import data using the read uncommitted isolation level can improve data transfer speed if the database supports it.
四、Sqoop export tool
导出工具可以将HDFS中的一组文件导出到RDBMS。 如果数据库中不存在目标表,则可能需要提前创建 。 Sqoop将根据用户指定的分隔符读取并解析这组文件作为输入。 默认情况下,它使用插入模式,这意味着要导出的行被转换为insert语句 ,以便将数据插入数据库。 如果数据处于调用模式 调用模式 下,则将数据转换为UPDATE语句以更新到数据库,然后为每个记录创建存储过程以插入数据。
Export tool can take a set of files in HDFS lead back to an RDBMS. If the target table does not exist in the database, you may need to create in advance. Sqoop will read and parse this set of files as input based on the delimiters specified by the user. By default, it uses insert mode, which means that the row to be exported is converted into an INSERT statement to insert the data into the database. Data is converted into an UPDATE statement to UPDATE to the database, if it is under the invocation pattern (call mode), then create stored procedures for each record to insert data.
(一)export arguments
1.参数详情介绍
| 参数 | 中文描述 | 英文重点/考点提示 |
|---|---|---|
--columns <col,col,col...> |
指定要导出到表的列 - 选择要导出的字段及其顺序 | 必考考点:列名用逗号分隔,必须与目标表的列对应,控制导出的数据列 |
--direct |
使用直接导出快速路径 - 绕过JDBC,使用数据库原生工具加速导出 | 重点考点:仅部分数据库支持(如MySQL的mysqldump),可大幅提升导出性能 |
--export-dir <dir> |
HDFS源数据路径 - 指定包含导出数据的HDFS目录 | 必考考点:必须指定且目录必须存在,是导出的数据来源 |
-m, --num-mappers <n> |
使用n个Map任务并行导出 - 控制导出作业的并行度 | 考点:默认4,影响导出速度和数据库连接压力 |
--table <table-name> |
要填充的目标表名 - 指定要导出数据到的数据库表 | 必考考点 :目标表必须已存在,与--call参数互斥 |
--call <stored-proc-name> |
要调用的存储过程 - 使用存储过程处理每条导出的记录 | 重点考点 :替代--table,每个记录调用一次存储过程,适合复杂逻辑 |
--update-key <col-name> |
用于更新的锚点列 - 指定用于匹配更新的列(通常是主键或唯一键) | 必考考点:指定后启用更新模式,多列用逗号分隔,所有列都匹配才更新 |
--update-mode <mode> |
指定更新模式 - 定义当数据库中存在不匹配键时如何处理新行 | 重点考点 :两种模式:updateonly(仅更新)和allowinsert(更新并插入) |
--input-null-string <null-string> |
字符串列的空值解释 - 指定HDFS数据中表示字符串NULL的字符串 | 考点:必须与HDFS数据中的NULL表示一致,否则NULL值会作为字符串导入 |
--input-null-non-string <null-string> |
非字符串列的空值解释 - 指定HDFS数据中表示非字符串NULL的字符串 | 考点 :与--input-null-string分开设置,因为数据库对字符串和非字符串NULL处理可能不同 |
--staging-table <staging-table-name> |
暂存表名 - 指定在插入目标表之前用于暂存数据的表 | 重点考点:用于确保导出事务完整性,避免部分失败导致数据不一致 |
--clear-staging-table |
清除暂存表 - 指示可以删除暂存表中的任何现有数据 | 考点 :必须与--staging-table一起使用,确保每次导出前暂存表是空的 |
--batch |
使用批处理模式 - 启用JDBC批处理执行,减少数据库往返次数 | 重点考点:提升导出性能,但可能增加内存使用,某些数据库驱动需单独配置 |
2.语法
bash
sqoop export < parameter > general < > export parameters
3.导出模式及注意事项
bash
# 模式1:Insert模式(默认,全量导出)
sqoop export --table employees --export-dir /data/emp
# 模式2:Update模式(仅更新已存在记录)
sqoop export --table employees --export-dir /data/updates --update-key id --update-mode updateonly
# 模式3:Upsert模式(更新并插入新记录)
sqoop export --table employees --export-dir /data/upserts --update-key id --update-mode allowinsert
# 模式4:Call模式(存储过程处理)
sqoop export --call process_employee --export-dir /data/emp
-
在使用导出工具时,必须使用
------export-dir参数指定源数据在HDFS中的目录,并通过-table指定要导出到数据库的目标表,或者通过------call指定要调用的存储过程。说明------table和------call不能同时使用。 -
When using the export tool, you must use the --export-dir parameter to specify the directory in which the source data is contained in HDFS, and specify the destination table to export to the database via --table, or specify the stored procedure to call via --call. Note --table and --call cannot be used at the same time.
-
默认情况下,将选择表中的所有列进行导出 。您还可以使用
------columns参数来指示要导出的列,并控制导出列的顺序,其值与逗号分隔的列名列表相对应。 -
By default, all columns in the table are selected for export. You can also use the --columns parameter to indicate which columns to export and to control the order in which columns are exported, with values that correspond to a comma-separated list of column names.
-
有些数据库还为导出提供了直接模式。使用------direct参数指定这个代码路径。这可能比标准的JDBC codepath性能更高。
-
Some databases provides a direct mode for exports as well. Use the --direct argument to specify this codepath. This may be higher-performance than the standard JDBC codepath.
-
由于Sqoop将导出过程分解为多个事务,因此一个失败的导出作业可能会导致部分数据提交到数据库。这可能会进一步导致后续的作业在某些情况下由于插入冲突而失败,或者在其他情况下导致重复数据。您可以通过------staging-table选项指定一个staging表来解决这个问题,这个选项充当一个用于staging导出数据的辅助表。在单个事务中,最终将暂存的数据移动到目标表。
-
Since Sqoop breaks down export process into multiple transactions, it is possible that a failed export job may result in partial data being committed to the database. This can further lead to subsequent jobs failing due to insert collisions in some cases, or lead to duplicated data in others. You can overcome this problem by specifying a staging table via the --staging-table option which acts as an auxiliary table that is used to stage exported data. The staged data is finally moved to the destination table in a single transaction.
-
为了使用暂存工具,用户必须在运行导出作业之前创建暂存表。此表必须在结构上与目标表相同。 这个表在运行导出作业之前应该是空的,或者必须指定
------clear-staging-table选项。如果暂存表中包含数据,并且指定了------clear-staging-table选项,那么Sqoop将在启动导出作业之前删除所有数据。 -
In order to use the staging facility, you must create the staging table prior to running the export job. This table must be structurally identical to the target table. This table should either be empty before the export job runs, or the --clear-staging-table option must be specified. If the staging table contains data and the --clear-staging-table option is specified, Sqoop will delete all of the data before starting the export job.
4.实例
(1)insert模式
bash
# 将HDFS数据导出到数据库表(全量插入)
sqoop export \
--connect jdbc:mysql://localhost:3306/testdb \
--username admin \
--password-file file:///home/admin/.dbpass \
--table employees_export \
--export-dir /user/hadoop/emp_data \
--columns "id,name,department,salary" \
--input-fields-terminated-by ',' \
-m 4
(2)update模式
bash
# 仅更新已存在的记录(基于id匹配)
sqoop export \
--connect jdbc:mysql://localhost:3306/testdb \
--username admin \
--password-file file:///home/admin/.dbpass \
--table employees \
--export-dir /user/hadoop/emp_updates \
--update-key id \ # 使用id列匹配记录
--update-mode updateonly \ # 仅更新,不插入新记录
--input-fields-terminated-by '\t' \
--batch \ # 启用批处理提升性能
-m 4
(3)upsert模式
bash
#更新存在的记录,插入新记录
sqoop export \
--connect jdbc:mysql://localhost:3306/testdb \
--table customers \
--export-dir /user/hadoop/customer_data \
--update-key "customer_id,region" \ # 复合键,两列都匹配才更新
--update-mode allowinsert \ # 允许插入新记录
--staging-table customers_stage \ # 使用暂存表确保一致性
--clear-staging-table \ # 导出前清空暂存表
--input-null-string '\\N' \
--input-null-non-string '\\N' \
-m 8
(4)call模式
bash
# 首先在数据库创建存储过程
-- MySQL示例
CREATE PROCEDURE upsert_employee(
IN p_id INT,
IN p_name VARCHAR(100),
IN p_salary DECIMAL(10,2)
)
BEGIN
INSERT INTO employees(id, name, salary)
VALUES(p_id, p_name, p_salary)
ON DUPLICATE KEY UPDATE
name = VALUES(name),
salary = VALUES(salary);
END;
# 使用call模式导出
sqoop export \
--connect jdbc:mysql://localhost:3306/testdb \
--call upsert_employee \ # 调用存储过程
--export-dir /user/hadoop/emp_proc_data \
--input-fields-terminated-by ',' \
-m 4
(二)Insert mode and update the model
导出数据有两种模式,插入模式和更新模式。 完全导出一般采用insert模式,即将数据导出到一个空表中。更新模式有时用于增量导出,更新模式有两种类型,默认是updateonly,也可以指定为allowinsert。
There are two modes for exporting data, insert mode and update mode. The insert mode is generally used for full export, that is, to export data to an empty table. The update mode is sometimes used for incremental export, and the update mode has two types, the default is updateonly, and it can also be specified as allowinsert.
1.insert模式
如果没有指定------update-key, Sqoop将使用默认的insert模式完成导出,它将把每条记录转换成一条insert语句到数据库表中,如果目标表有一些约束,例如:唯一约束,在使用insert模式时要小心,以避免违反这些约束。如果一条记录未能插入,则整个导出作业将最终失败。这种插入模式通常用于将数据导出到一个新的空表中。
If not specified --update-key, Sqoop will complete the export using the default insert mode, it will convert each record into an INSERT statement to the database table, if the target table has some constraints such as unique constraints, be careful when using insert mode to avoid violating those constraints. If one record fails to insert, the entire export job will eventually fail. This insert mode is typically used to export data to a new, empty table.
2.update模式
如果指定------update-key,导出将使用update模式完成,默认的更新模式是updateonly,或者你可以添加------update-mode updateonly来明确设置它,在updateonly模式下,Sqoop将只修改数据库表中已经存在的数据集,作为输入的每条记录将被转换为update语句来修改现有的记录,要修改的记录由------update-key指定的列决定,如果UPDATE语句在数据库中没有对应的记录,它不会插入新数据,但也不会报告错误,导出操作将继续。简而言之,数据库中不导出新的记录,只更新已存在的记录。您还可以通过添加------update-mode alllowinsert来指定更新模式为alllowinsert,然后您可以更新现有记录并同时插入新记录。对每条记录执行更新操作还是插入操作由------update-key指定的列决定。
If --update-key is specified, the export will be done using update mode, the default UPDATE mode is updateonly, or you can add --update-mode updateonly to set it explicitly, in updateonly mode, Sqoop will only modify the dataset that already exists in the database table, each record as input will be converted into a UPDATE statement to modify the existing record, which record to modify is determined by the column specified by --update-key, if a UPDATE statement does not have a corresponding record in the database, it will not insert new data, but it will not report an error, and the export operation will continue. In shorten brief, new records are not exported in the database, but only the existed records are updated. You can also specify the update mode as alllowinsert by adding the --update-mode alllowinsert, then you can update existing records and insert new records at the same time. Whether an update operation or an insert operation is performed on each record is determined by the column specified by --update-key.
3.几种模式的对比
| 模式 | 参数组合 | 特点 | 适用场景 |
|---|---|---|---|
| Insert | 默认,无--update-key |
插入所有记录,重复主键会失败 | 目标表为空或确保无重复 |
| Updateonly | --update-key + --update-mode updateonly |
只更新存在的记录,忽略新记录 | 增量更新已有数据 |
| Allowinsert | --update-key + --update-mode allowinsert |
更新存在的记录,插入新记录 | 全量同步,合并数据 |
| Call | --call |
每条记录调用存储过程 | 需要复杂业务逻辑处理 |
4.重要参数的解释
- 需要
------export-dir参数和------table或------call中的一个。它们指定了要填充到数据库中的表(或要调用的存储过程),以及包含源数据的HDFS目录。The --export-dir argument and one of --table or --call are required. These specify the table to populate in the database (or the stored procedure to call), and the directory in HDFS that contains the source data. ------update-mode的合法值包括updateonly(默认值)和allowinsert。默认模式是updateonly,只存在数据更新,不存在数据插入。如果将------update-mode指定为allowinsert,则可以在更新数据时将目标数据库中不存在的数据导出到数据库表。Legal values for --update-mode include updateonly (default) and allowinsert. The default mode is updateonly, only data updates exist, no data insertions. If you specify --update-mode to allowinsert, you can export data that does not exist in the target database to the database table while updating the data.------update-key指定更新时引用的列,如果有多个列,则用逗号分隔。请注意,只有当所有的参考列都匹配时,才会发生更新。--update-key Specifies the column to refer to when performing the update, separated by commas if there are multiple columns. Note that update will only occur when all reference columns match.
(三)Invocation pattern(call mode)
在调用模型(调用模式)下,Sqoop为每次调用记录一个存储过程以插入或更新数据。 存储过程需要提前在数据库上创建。 例如,需求是将数据导出到MySQL数据库的foo bar表,在前面创建的存储过程barproc如下所示:
In call mode, Sqoop calls a stored procedure for each record to insert or update data. Stored procedures need to be created on the database in advance. For example, if you want to export data to a bar table under mySQL's foo database, create a stored procedure named barproc as follows:
bash
use foo;
delimiter $$
CREATE PROCEDURE barproc (IN c1 TYPE1, IN c2 TYPE2...)
BEGIN
INSERT INTO barproc(col1, col2...) VALUES(c1, c2...);
END$$
delimiter ;
Then write the Sqoop command, Sqoop will call a stored procedure named barproc for exporting each record in /results/bar_data.
bash
sqoop-export --connect jdbc:mysql://db.example.com/foo --call barproc \--export-dir /results/bar_data
(四)Export and Transaction
-
Sqoop导出数据是通过创建多个连接到数据库将数据写入并行数据库 ,每个连接是开放的,其他连接是隔离的事务。
-
Sqoop export data is by creating multiple connections to the database will write data parallel database, each connection is open and other connecting isolated transactions.
-
Sqoop导出操作将输入INSERT语句,每个INSERT语句最多插入100条记录。
-
负责向数据库写入的任务将每10,000条记录生成一个事务提交,确保事务缓冲区不会无限制地增长,也不会冒内存耗尽的风险。 所以整个导出操作不是原子操作,因为在整个导出过程未完成之前,有一些数据是立即对外可见的导出。
-
Sqoop export operation will enter into the INSERT statement, each INSERT statement to INSERT a maximum of100 records.
The task responsible for writing to the database will generate a transaction commit every 10,000 records, ensuring that the
transaction buffer does not grow without limit and risk running out of memory. So the whole export operation is not atomic
operation, because before the whole process ofexport unfinished, has some ofthe data is immediately visible to foreign export.
(五)Export Failure Handling
导致导出操作失败的可能原因有:
- Hadoop集群与数据库的连接中断(可能是硬件故障,也可能是服务器软件崩溃)Loss of connectivity from the Hadoop cluster to the database (either due to hardware fault, or server software crashes)
- 试图插入违反一致性约束的行 (例如,插入了一个重复的主键值)Attempting to INSERT a row which violates a consistency constraint (for example, inserting a duplicate primary key value)
- 试图从HDFS源数据中解析不完整或格式错误的记录 Attempting to parse an incomplete or malformed record from the HDFS source data
- 试图使用不正确的分隔符(,;:-)解析记录 Attempting to parse records using incorrect delimiters(, ; : -)
- 容量问题(例如RAM或磁盘空间不足) Capacity issues (such as insufficient RAM or disk space)
(六)Exporting Data from Hive
Sqoop不支持直接从Hive表导出数据,只能使用------export-dir选项从HDFS导出数据,步骤如下。
- 确定要导出的Hive表的结构,是否为分区表,是否启用压缩等。Determine the structure of the Hive table to be exported, whether it is a partitioned table, whether compression is enabled, etc.
- 确定Hive表中数据在HDFS中的实际存储位置。Determine the actual storage location in HDFS for the data in the Hive table.
- 确定源数据的定界符设置。Determine the delimiter settings for the source data.
- 根据Hive表在数据库中创建一个相同结构的表用于导出数据。 Create a table with the same structure in the database based on the Hive table for exporting data.
- 使用Sqoop导出工具编写一条命令,将数据导出到数据库的目标表中 Write a command for exporting the data into the target table in the database using the Sqoop export tool,
(七)Exporting Data from HBase
Sqoop不支持直接从HBase表导出数据,但可以通过Hive表间接导出数据,如下所示
Sqoop does not support exporting data directly from HBase tables, but it can be done indirectly with the help of Hive tables, as follows:
- 在Hive中基于HBase表创建一个外部表。Create an external tables based on HBase table in Hive.
- 基于刚刚创建的Hive外部表创建Hive内部表。Create the Hive internal table based on the Hive external table we just created.
- 从Hive外部表加载数据到Hive内部表。 Load the data from the Hive external table into the Hive internal table.
- 将数据从Hive内部表导出到预先在数据库中创建的目标表。 Export the data from the Hive internal table to the target table that we created in advance in the database.
- 如有必要,清理Hive临时表。 Clean up the Hive temporary table if necessary.
(八)Export Results Validation
跟导入的validation几乎一样 参考即可。这些接口可以在 org.apache.sqoop.validation 包中找到。
(九)The export performance optimization
- 当目标数据库支持时,在命令中使用------direct参数可以提高导出性能。When target database supports, using the --direct parameter in the command may improve the export performance.
- 默认情况下,Sqoop的export函数对导出的每一行数据执行一条INSERT语句。当数据量较大时,如果想提高导出速度,可以设置一条INSERT语句,批量插入多行数据:By default, Sqoop's export function executes one INSERT statement for each row of data exported. If you want to improve the export speed when the data volume is large, you can set a single INSERT statement to insert multiple rows of data in bulk:
- a.Add
--batchoption to the command to enable JDBC batch processing在命令中添加------batch选项以启用JDBC批处理 - b.Modify the number of record rows that can be exported in bulk for each SQL statement 修改每条SQL语句可以批量导出的记录行数
- c.Set the number of query statements submitted by a single transaction 设置单个事务提交的查询语句的数量
- -Dsqoop.export.statements.per。transaction=10000,我们可以指定在单个事务中执行多少INSERT语句。较高的值通常有助于提高性能,但这取决于数据库。With
-Dsqoop.export.statements.per. transaction=10000, we can specify how many INSERT statements will be executed in a single transaction. A higher value generally helps improve the performance, but depending on the database. - 通过添加
-Djdbc.transaction。isolation=TRANSACTION_READ_UNCOMMITTED在Sqoop export命令中,可以将数据库的事务隔离级别更改为read uncommitted,以提高导出速度,并以降低事务隔离级别为代价避免死锁和其他问题。By adding -Djdbc.transaction. isolation=TRANSACTION_READ_UNCOMMITTEDin the Sqoop export command, you can change the transaction isolation level of the database to read uncommitted to improve the export speed and to avoid deadlocks and other problems at the cost of lowering the transaction isolation level.
五、Sqoop job tools
有些Sqoop命令可能需要反复执行,尤其是增量导入往往是周期性执行的,对于这样的场景,往往需要将Sqoop保存为命令操作,以这样的形式执行,以便下次执行更加容易和方便。 本节向您展示如何使用sqoop - job工具将执行sqoop命令的所有配置信息定义成一个保存操作(Saved job),保存作业一旦定义,就可以在以后的任何时候执行。 默认情况下,作业的描述,如元数据。 配置Sqoop还可以使用共享元数据存储库来存储信息,以便集群中的所有用户都可以使用保存操作。
(一)参数介绍
1.参数详情
| 参数 | 中文描述 | 英文重点/考点提示 |
|---|---|---|
--create <job-id> |
创建新保存作业 - 通过指定作业ID定义一个新作业,后面需要用--分隔并指定子工具名和参数 |
必考考点 :语法格式为sqoop job --create <job-id> -- [subtool] [args],--是分隔符关键 |
--delete <job-id> |
删除保存的作业 - 删除指定作业ID的保存作业 | 考点:删除后不可恢复,通常用于清理不再需要的作业定义 |
--exec <job-id> |
执行保存的作业 - 执行通过--create创建的保存作业 |
重点考点 :会自动维护增量导入的--last-value,是实现自动化增量导入的关键 |
--show <job-id> |
显示作业参数 - 显示保存作业的详细参数配置信息 | 考点:用于检查作业配置,查看实际执行的命令和参数 |
--list |
列出所有保存作业 - 显示所有已保存作业的ID列表 | 必考考点 :查看现有作业,作业默认保存在$HOME/.sqoop/目录下 |
2.语法
bash
sqoop job (generic-args) (job-args) [-- [subtool-name] (subtool-args)]
3.实例
(1)创建增量导入作业
bash
sqoop job --create daily_import \
-- import \ # -- 后面跟子工具名
--connect jdbc:mysql://localhost:3306/testdb \
--table sales \
--incremental append \
--check-column sale_id \
--last-value 0 \ # 初始值,执行时会自动更新
--target-dir /user/hadoop/sales \
-m 4
(2)作业执行与增量导入
bash
# 执行作业(自动管理--last-value)
sqoop job --exec daily_import
# 执行过程:
# 1. 读取作业定义
# 2. 获取上次执行的--last-value
# 3. 使用新的--last-value执行导入
# 4. 更新存储的--last-value为本次导入的最大值
4.有关命令模板
(1)创建基本导入作业
bash
# 创建全量导入作业
sqoop job --create full_import \
-- import \
--connect jdbc:mysql://localhost:3306/testdb \
--username etl_user \
--password-file file:///home/etl/.dbpass \
--table customers \
--target-dir /user/hadoop/customers_full \
--delete-target-dir \
-m 4
(2)创建增量导入作业
bash
# 创建基于时间戳的增量导入作业
sqoop job --create incremental_orders \
-- import \
--connect jdbc:mysql://localhost:3306/orderdb \
--table orders \
--incremental lastmodified \ # 基于时间戳的增量
--check-column update_time \ # 检查列(时间戳类型)
--last-value "2023-01-01 00:00:00" \ # 初始值
--merge-key order_id \ # 合并键
--target-dir /user/hadoop/orders_incremental \
--append \ # 追加模式
-m 4
(3)创建导出作业
bash
# 创建数据导出作业
sqoop job --create daily_export \
-- export \
--connect jdbc:mysql://localhost:3306/warehouse \
--table daily_summary \
--export-dir /user/hadoop/daily_results \
--input-fields-terminated-by ',' \
--update-key date_key \
--update-mode allowinsert \
--staging-table temp_summary \
--clear-staging-table \
-m 2
(4)作业管理
bash
# 列出所有作业
sqoop job --list
# 输出:daily_import
# incremental_orders
# daily_export
# 查看作业详情
sqoop job --show daily_import
# 执行作业
sqoop job --exec daily_import
# 删除作业
sqoop job --delete daily_export
5.作业存储位置
bash
# 默认存储位置
$HOME/.sqoop/ # 用户主目录下的.sqoop目录
# 查看作业文件
ls ~/.sqoop/ # 包含作业定义和状态文件
# 作业元数据文件
~/.sqoop/metadata/ # 存储作业元数据
6.--meta--connect
(1)参数详情
| 参数 | 中文描述 | 英文重点/考点提示 |
|---|---|---|
--meta-connect <jdbc-uri> |
指定连接元数据存储的JDBC连接字符串 - 用于连接到共享的Sqoop元数据存储服务 | 重点考点 :用于连接远程共享元数据存储,默认使用本地HSQLDB存储(jdbc:hsqldb:file:/path) |
bash
```bash
# 连接到远程共享元数据存储
--meta-connect jdbc:hsqldb:hsql://metaserver.example.com:16000/sqoop
(2) 存储配置属性
| 属性名称 | 默认值 | 中文描述 | 考点提示 |
|---|---|---|---|
sqoop.metastore.server.location |
无 | 元数据存储文件磁盘位置 - 指定元数据文件在本地文件系统的存储目录 | 必考考点:必须指向本地文件系统目录,用于持久化存储元数据 |
sqoop.metastore.server.port |
16000 | 元数据存储服务端口 - 指定元数据存储服务监听的TCP/IP端口 | 必考考点:默认端口16000,可修改以适配网络环境 |
sqoop.metastore.client.enable.autoconnect |
false | 启用自动连接 - 设置为true时,客户端自动连接元数据存储,无需每次指定--meta-connect |
重点考点:简化操作,实现透明连接 |
sqoop.metastore.client.autoconnect.url |
无 | 自动连接URL - 指定自动连接时使用的元数据存储URL地址 | 考点:必须配置正确的JDBC URL,否则回退到私有元数据存储 |
(3)元数据存储服务管理命令
| 命令 | 中文描述 | 考点提示 |
|---|---|---|
sqoop metastore |
启动元数据存储服务 - 启动共享元数据存储服务进程 | 必考考点:启动后服务监听指定端口(默认16000) |
sqoop metastore --shutdown |
关闭元数据存储服务 - 停止运行的元数据存储服务 | 考点:优雅关闭服务,确保数据一致性 |
两种元数据存储模式对比:
- 私有模式(默认):每个用户独立,存储在$HOME/.sqoop/
- 共享模式:多用户共享,通过TCP/IP访问,需启动服务
(二)sqoop merge tool
合并工具允许你合并两个数据集,其中一个数据集的条目会覆盖旧数据集的条目。The merge tool allows you to combine two datasets where entries in one dataset should overwrite entries of an older dataset.
1.具体参数
| 参数 | 中文描述 | 英文重点/考点提示 |
|---|---|---|
--class-name <class> |
指定合并作业中使用的记录特定类名 - 用于反序列化数据的Java类名 | 考点 :通常由sqoop codegen自动生成,格式如Employee或com.example.Employee |
--jar-file <file> |
指定加载记录类的JAR文件 - 包含记录类的JAR包路径 | 必考考点 :必须包含--class-name指定的类,可以是本地路径或HDFS路径 |
--merge-key <col> |
指定用作合并键的列名 - 用于匹配新旧数据集记录的主键列 | 重点考点:必须是唯一且在所有记录中存在的列,用于确定哪条记录覆盖哪条 |
--new-data <path> |
指定新数据集的路径 - HDFS中包含新数据的目录路径 | 必考考点:通常是最近增量导入的数据,将覆盖旧数据集中相同键的记录 |
--onto <path> |
指定旧数据集的路径 - HDFS中包含旧数据的目录路径 | 重点考点:被覆盖的基础数据集,新数据集中没有的记录将保留 |
--target-dir <path> |
指定合并输出的目标路径 - HDFS中合并后数据的存储目录 | 考点 :不能与--new-data或--onto相同,必须是新目录 |
2.语法
bash
sqoop merge (generic-args) (merge-args)
3.工作原理
bash
```bash
# Merge 工具执行流程:
# 1. 读取旧数据集(--onto指定)
# 2. 读取新数据集(--new-data指定)
# 3. 根据合并键(--merge-key)匹配记录
# 4. 新数据集中相同键的记录覆盖旧数据集中的记录
# 5. 将合并结果写入目标目录(--target-dir)
# 数据流示例:
旧数据集: [{id:1, name:"Alice", ver:1}, {id:2, name:"Bob", ver:1}]
新数据集: [{id:1, name:"Alice", ver:2}, {id:3, name:"Charlie", ver:1}]
合并结果: [{id:1, name:"Alice", ver:2}, {id:2, name:"Bob", ver:1}, {id:3, name:"Charlie", ver:1}]
4.Merge 工具使用场景
(1)增量导入新数据
bash
sqoop import \
--table orders \
--incremental lastmodified \
--check-column update_time \
--last-value "2023-12-31" \
--target-dir /user/hadoop/orders_new \
--append
(2)合并新旧数据
bash
sqoop merge \
--new-data /user/hadoop/orders_new \ # 新数据
--onto /user/hadoop/orders_old \ # 旧数据
--target-dir /user/hadoop/orders_merged \ # 合并结果
--merge-key order_id \ # 合并键(主键)
--class-name Order \
--jar-file /path/to/order.jar
(3)记录类与JAR文件
bash
# 需要先通过codegen生成记录类
sqoop codegen \
--connect jdbc:mysql://localhost:3306/testdb \
--table orders \
--class-name Order \
--outdir /tmp/codegen \
--bindir /tmp/jars
5.Merge 使用实例
(1)基本合并操作
bash
#合并两个数据集,用新数据覆盖旧数据
sqoop merge \
--new-data /user/hadoop/customers_new \ # 新数据路径
--onto /user/hadoop/customers_old \ # 旧数据路径
--target-dir /user/hadoop/customers_merged \ # 合并结果路径
--merge-key customer_id \ # 合并键(主键)
--class-name Customer \ # 记录类名
--jar-file /user/hadoop/jars/customer.jar # JAR文件路径
-m 4 # Map任务数
(2)与增量导入配合使用
bash
# 完整工作流程:增量导入 -> 合并
# 步骤1:增量导入新数据(lastmodified模式)
sqoop import \
--connect jdbc:mysql://localhost:3306/testdb \
--table products \
--incremental lastmodified \
--check-column last_updated \
--last-value "2023-12-31 23:59:59" \
--target-dir /user/hadoop/products_incremental \
--append \
-m 4
# 步骤2:生成记录类(如果还没有)
sqoop codegen \
--connect jdbc:mysql://localhost:3306/testdb \
--table products \
--class-name Product \
--outdir /tmp/product_codegen \
--bindir /tmp/product_jars
# 步骤3:合并数据
sqoop merge \
--new-data /user/hadoop/products_incremental \
--onto /user/hadoop/products_base \
--target-dir /user/hadoop/products_current \
--merge-key product_id \
--class-name Product \
--jar-file /tmp/product_jars/products.jar
-
Sqoop自动生成代码来解析和解释包含导出回数据库的数据的文件记录。 Sqoop automatically generates code to parse and interpret records of the files containing the data to be exported back to the database.
-
如果创建文件时使用了非默认的定界符(字段用逗号分隔,记录用换行符分隔),则应该再次指定相同的定界符,以便Sqoop解析文件。 If these files were created with non-default delimiters (comma-separated fields with newline-separated records), you should specify the same delimiters again so that Sqoop can parse your files.
(三)Sqoop Code Generation Tool
1.参数
| 参数 | 中文描述 | 英文重点/考点提示 |
|---|---|---|
--bindir <dir> |
编译对象的输出目录 - 指定编译后的.class文件存放目录 | 考点 :通常与--outdir配合使用,--outdir放源码,--bindir放编译后的类文件 |
--class-name <name> |
设置生成的类名 - 指定生成的Java类的名称,会覆盖--package-name的效果 |
重点考点 :与--jar-file一起使用时,用于指定输入类名,而不是生成新类 |
--jar-file <file> |
禁用代码生成;使用指定的jar - 使用已有的JAR文件,而不是生成新的代码 | 必考考点 :与--class-name一起使用,跳过代码生成步骤,直接使用现有的JAR和类 |
--outdir <dir> |
生成代码的输出目录 - 指定生成的Java源代码文件的目录 | 考点:默认在当前目录生成,可通过此参数指定其他目录 |
--package-name <name> |
将自动生成的类放入指定包 - 设置生成类的Java包名 | 重点考点 :如果不指定,则使用默认包(无包名);如果指定--class-name则覆盖此参数 |
--map-column-java <m> |
覆盖默认的SQL类型到Java类型的映射 - 为指定列自定义Java数据类型 | 高级考点 :格式为列名=Java类型,多个列用逗号分隔,如id=Integer,name=String |
2.Codegen工具使用
bash
```bash
# Codegen 工具用于生成与数据库表交互的Java类
# 这些类用于在Sqoop导入/导出时序列化和反序列化数据
# 基本用法:
sqoop codegen --connect jdbc:mysql://localhost:3306/testdb --table employees
3.使用场景
bash
# 场景1:生成特定包名的类
sqoop codegen \
--connect jdbc:mysql://localhost:3306/testdb \
--table employees \
--package-name com.example.model \
--outdir /tmp/src \
--bindir /tmp/classes
# 场景2:使用现有JAR文件(跳过代码生成)
sqoop import \
--connect jdbc:mysql://localhost:3306/testdb \
--table employees \
--jar-file /path/to/existing.jar \
--class-name com.example.Employee
生成的类名通常与表名相同 ,也可以使用------class-name选项指定。类似地,你可以用------package-name选项指定包名。The generated class name is typically the same as the table name, you can also specify it by using --class-name option. Similarly, you can specify just the package name with --package-name option.
总结
Apache Sqoop是一个用于在Hadoop分布式文件系统(HDFS)和关系型数据库管理系统(RDBMS)之间进行高效批量数据传输的工具。2012年3月成为Apache顶级项目支持HDFS、Hive、HBase等Hadoop生态组件支持MySQL、Oracle、PostgreSQL等主流数据库开源工具,广泛用于大数据生态系统