我想在 Amazon EMR 集群中使用 Spark 连接到 Amazon Redshift 集群。
解决方法
**注意:**在开始之前,请务必配置您的 Amazon Redshift 集群。然后,使用 Spark 启动 Amazon EMR 6.4 或更高版本的集群。
要在您的 Amazon EMR 集群中使用 Spark 连接到 Amazon Redshift 集群,请完成以下步骤:
测试 Amazon EMR 集群和 Amazon Redshift 集群之间的连接
-
确认 Amazon Redshift 集群的安全组入站规则允许在 TCP 端口 5439 上使用 Amazon EMR 主安全组、核心安全组和任务安全组。
**注意:**如果您的集群部署在两个不同的 Amazon Virtual Private Clouds (Amazon VPC) 中,则请配置 Amazon VPC 对等连接。
-
要连接到 Amazon EMR 主节点,请使用 SSH。然后,运行以下 telnet 命令:
telnet example-redshift-endpoint 5439
**注意:**请将 example-redshift-endpoint 替换为您的 Amazon Redshift 集群端点。
输出示例:
telnet redshift-cluster-1.XXXXX.us-east-1.redshift.amazonaws.com 5439
Trying 172.31.48.21...
Connected to redshift-cluster-1.XXXXX.us-east-1.redshift.amazonaws.com.
Escape character is '^]'.
在 Amazon EMR 6.4.0 或更高版本中使用 Spark 连接到 Amazon Redshift 集群
完成以下步骤:
- 要连接到 Amazon EMR 主节点,请使用 SSH。
- 要读取 Amazon Redshift 表,请使用 JDBC 连接器。有关详细信息,请参阅连接器参数。
PySpark 示例:
[hadoop@ip-10-10-10-10 ~]$ pyspark
>>> from pyspark.sql import SQLContext
>>> sql_context = SQLContext(sc)
>>> url = "jdbc:redshift://<redshift-endpoint>:5439/dev?user=<user>&password=<password>"
>>> df = sql_context.read \
.format("io.github.spark_redshift_community.spark.redshift") \
.option("url", url) \
.option("query", "select * from table") \
.option("tempdir", "<tempdir>") \
.option("aws_iam_role", "<iam_role>") \
.load()
>>> df.show(2)
Spark-shell example:
[hadoop@ip-192-168-1-113 ~]$ spark-shell
scala> import org.apache.spark.sql._
scala> val sql_context = new SQLContext(sc)
scala> val url = "jdbc:redshift://<redshift-endpoint>:5439/dev?user=<user>&password=<password>"
scala> val df = sql_context.read.format("io.github.spark_redshift_community.spark.redshift").option("url", url).option("query", "select * from table").option("tempdir", "<tempdir>").option("aws_iam_role", "<iam_role>").load()
scala> df.show(2)
注意: 有关管理 JDBC 连接中使用的用户凭证的其他安全选项,请参阅 Amazon Redshift 中的 Identity and Access Management。
相关信息
将适用于 Apache Spark 的 Amazon Redshift 集成与 Amazon EMR 结合使用