pyspark 从postgresql读取数据

因为我安装的是spark 3.5.6,所以需要安装

bash 复制代码
pip install pyspark==3.5.6

Pyspark从postgresql读数据

python 复制代码
import time
from pyspark.sql import DataFrame, SparkSession,DataFrameReader
from pyspark.sql.functions import to_json, struct

spark: SparkSession.Builder = SparkSession.builder

session: SparkSession = spark.appName("Python Spark SQL data source example") \
        .config("spark.jars", r"C:\Users\84977\Downloads\postgresql-42.7.6.jar") \
        .master("spark://192.168.220.132:7077")\
        .getOrCreate()
        
last_max_id = 0  # 保存上次读取的最大ID

page_size= 2

while True:
    query = f"""
        (SELECT * FROM public.complexjson
         WHERE id > {last_max_id}
         ORDER BY id ASC
         LIMIT {page_size}) as t
    """

    df: DataFrame = session.read \
        .format("jdbc") \
        .option("url", "jdbc:postgresql://192.168.220.130:32222/postgresdb") \
        .option("dbtable", query) \
        .option("driver", "org.postgresql.Driver") \
        .option("user", "postgresadmin") \
        .option("password", "admin123") \
        .load()

    if df.count() > 0:
        df.show(truncate=False)

        json_df = df.select(to_json(struct("*")).alias("json"))
        for row in json_df.collect():
            print(row["json"])

        # 更新 last_max_id
        max_id = df.agg({"id": "max"}).collect()[0][0]
        last_max_id = max_id

    time.sleep(10)  # 每10秒轮询一次
相关推荐
gsfl1 天前
Redis 缓存
数据库·redis·缓存
恒悦sunsite1 天前
Ubuntu之apt安装ClickHouse数据库
数据库·clickhouse·ubuntu·列式存储·8123
奥尔特星云大使1 天前
MySQL 慢查询日志slow query log
android·数据库·mysql·adb·慢日志·slow query log
来自宇宙的曹先生1 天前
MySQL 存储引擎 API
数据库·mysql
间彧1 天前
MySQL Performance Schema详解与实战应用
数据库
间彧1 天前
MySQL Exporter采集的关键指标有哪些,如何解读这些指标?
数据库
weixin_446260851 天前
Django - 让开发变得简单高效的Web框架
前端·数据库·django
mpHH1 天前
babelfish for postgresql 分析--todo
数据库·postgresql
zizisuo1 天前
解决在使用Lombok时maven install 找不到符号的问题
java·数据库·maven
程序边界1 天前
国产之光!金仓数据库KingbaseES Oracle兼容性深度体验大赏
数据库·oracle