在MaxCompute中使用PyODPS

在MaxCompute中使用PyODPS

1 简单介绍MaxCompute、DataWorks以及PyODPS

1.1 什么是MaxCompute

大数据计算服务(MaxCompute,原名ODPS)是一种快速、完全托管的EB级数据仓库解决方案。
DataWorks和MaxCompute关系紧密:DataWorks为MaxCompute提供一站式的数据同步、业务流程设计、数据开发、管理和运维功能。

1.2 什么是DataWorks

DataWorks(数据工场,原大数据开发套件)是阿里云重要的PaaS(Platform-as-a-Service)平台产品,提供数据集成、数据开发、数据地图、数据质量和数据服务等全方位的产品服务,一站式开发管理的界面,帮助企业专注于数据价值的挖掘和探索。
DataWorks支持多种计算和存储引擎服务,包括离线计算MaxCompute、开源大数据引擎E-MapReduce、实时计算(基于Flink)、机器学习PAI、图计算服务Graph Compute和交互式分析服务等,并且支持用户自定义接入计算和存储服务。可以使用DataWorks,对数据进行传输、转换和集成等操作,从不同的数据存储引入数据,并进行转化和开发,最后将处理好的数据同步至其它数据系统。

1.3 什么是PyODPS

PyODPS是MaxCompute的Python版本的SDK,提供简单方便的Python编程接口。

2 数据的读取和写入

2.1 可能会遇到的问题以及解决方法

  • 获取数据量受限
    在Maxcompute平台上获取sql查询结果是一个Restful请求,由于一次 Restful 请求的返回数据有限,且一次性获取全量数据到本地时可能将内存撑爆等问题,Maxcompute SQL 的查询结果条数是受限的,具体的数值为 project 上的配置项 READ_TABLE_MAX_ROW (默认为 10000)。这就会出现明明我们的查询结果 2W 条,最后却在 Maxcompute Console 或者 Logview 上只看到 1W条 的情况了。

  • 解决方法 Instance Tunnel
    Instance Tunnel提供使用Tunnel来下载SQL查询结果的功能可直接获取查询结果。

2 例子

from odps import ODPS
import pandas as pd
from odps.models import Schema, Column, Partition
from collections import defaultdict
from dateutil.relativedelta import relativedelta

options.tunnel.use_instance_tunnel = True # 使用instance tunnel接口
options.tunnel.limit_instance_tunnel = False  # 关闭limit限制,读取全部数据
options.allow_antique_date = True # 允许很早的时间

# 直接获取表
t = o.get_table('tablename')

# 执行sql语句
# 也可在open_reader(tunnel=True, limit=False)中设置调用instance tunnel接口,和关闭limit限制
def exe_sql(sql):
    data = []
    with o.execute_sql(sql).open_reader() as reader:
        d = defaultdict(list)
        for record in reader:
            for res in record:
                d[res[0]].append(res[1])
        data = pd.DataFrame.from_dict(d, orient='index').T
    return data

# 保存DataFrame
def save_table(tablename, df):
    m = []
    for _,record in df.iterrows():
        records = record.values.tolist()
        m.append(list(record))
    o.write_table(tablename,m)
posted @ 2020-10-28 16:56  spacescp  阅读(649)  评论(0)    收藏  举报