spark-submit运行Python代码的结构如下,出现了数据倾斜问题,即每次访问接口,得到的json数据量不同,该如何修改代码结构:a = [] b = [] for url in url_list: response = requests.get(url, params=params) html = response.text data = json.loads(html) # 对Data做相关数据处理 ...... a.append(data['data']['key1']) b.append(data['data']['key2']) answer_pd= pd.DataFrame() answer_pd['a'] = a answer_pd['b'] = b conf = SparkConf().setAppName("APP").setMaster("yarn").setSparkHome("/usr/xxx/xx/xxx") sc = SparkContext(conf=conf) hc = HiveContext(sc) dt = 'database.table' # 数据库和表名 hc.setConf("hive.exec.dynamic.partition.mode", "nonstrict") hc.createDataFrame(answer_pd).write.mode("append").insertInto(dt)
时间: 2024-04-14 20:26:30 浏览: 103
为了解决数据倾斜问题,可以考虑对URL列表进行分片,然后将每个分片中的URL并行处理。这样可以将请求并行化,减少数据倾斜现象的影响。下面是修改后的代码结构:
```python
from pyspark.sql import SparkSession
from pyspark.sql.functions import col
import pandas as pd
# 将URL列表进行分片,每个分片包含一部分URL
sliced_url_list = [url_list[i:i+slice_size] for i in range(0, len(url_list), slice_size)]
spark = SparkSession.builder \
.appName("APP") \
.master("yarn") \
.getOrCreate()
for sliced_urls in sliced_url_list:
# 将sliced_urls转化为一个RDD
rdd = spark.sparkContext.parallelize(sliced_urls)
# 使用flatMap函数对每个URL发送HTTP请求并处理数据
result_rdd = rdd.flatMap(lambda url: process_url(url, params))
# 将result_rdd转化为DataFrame
df = result_rdd.toDF(["a", "b"])
# 将DataFrame写入Hive表
dt = 'database.table' # 数据库和表名
df.write.mode("append").insertInto(dt)
spark.stop()
```
在上述代码中,我们将URL列表进行分片,并使用`parallelize`方法将每个分片转化为一个RDD。然后,使用`flatMap`函数对每个URL进行处理,并生成一个包含"a"和"b"字段的RDD(即`result_rdd`)。接着,将`result_rdd`转化为DataFrame,并使用`insertInto`方法将DataFrame写入Hive表。
这样,通过将URL分片并行处理,可以减少数据倾斜问题的影响,并提高处理效率。注意,`process_url`函数需要根据实际需求进行实现,以实现对URL的处理和数据提取。
阅读全文
相关推荐



















