from odps import options
import time
#project = odps.get_project()
# 表操作
#表清單
for table in odps.list_tables():
print table
#表是否存在
if odps.exist_table('ods_orders'):
print 1
else:
print 0
#獲取表
odps.get_table('ods_orders',project='ah_test')
#創建表
table = odps.create_table('my_new_table','num bigint,num2 double',if_not_exists=True) #一般表
table = odps.create_table('my_new_table',('num bigint,num2 double','pt string'),if_not_exists=True) #分區表
options.sql.use_odps2_extension = True #新數據類型支持開關
#同步表更新
table.reload()
#獲取表數據
table = odps.get_table('ods_orders')
with table.open_reader(partition='pt=20191118') as reader:
count = reader.count
for record in reader[5:10]:
print (record)
#寫入數據
with table.open_writer(partition='pt=20191120,pt1=...',create_partition=True) as writer:
records = [[..],[..]]
writer.write(records)
create_partition參數指定創建分區
#刪除表
odps.delete_table('my_table_name',if_exists=True)
odps.drop() #Table對象存在的時候可以直接drop函數
#創建DataFrame
df = table.to_df()
#判斷是否分區表
if table.schema.partitions:
print(table.name)
#遍歷表全部分區
for partition in table.partitions:
print(partition.name)
#遍歷二級分區
for partition in table.iterate_partitions(spec='pt=20191118'):
print(partition.name)
#判斷分區是否存在
table.exist_partition('pt=20191118')
#獲取分區
partition = table.get_partition('pt=20191118')
#創建分區
table.create_partition('pt=20191119',if_not_exists=True)
#刪除分區
table.delete_partition('pt=20191119',if_exists=True) #存在時刪除
partition.drop()
SQL操作
#執行SQL
odps.execute_sql('select * from ods_orders ') #同步方式
odps.run_sql('select * from ods_orders') #異步方式
print(instance.get_logview_address()) #獲取logview地址
instance.wait_for_success() #阻塞直到完成
#設置參數
odps.execute_sql(sql,hints={'odps.sql.mapper.split.size':16}) #設置hints運行參數
或
from odps import options
options.sql.setting = {'odps.sql.mapper.split.size':16}
odps.execute_sql(sql)
#讀取SQL執行結果
options.tunnel.use_instance_tunnel == True #控制通道
tunnel.limit_instance_tunnel = True #限制下載數據的規模
sql = "select * from ods_orders where pt='20191118' limit 10"
instance = odps.run_sql(sql)
with instance.open_reader(tunnel=True) as reader: #tunnel參數
for record in reader:
print(record['o_orderkey'])
或
with instance.open_reader() as reader:
print(reader.raw)
#設置alias UDF引用的資源動態變化,可以將舊的資源名到新的資源,不需要重建刪除或創建新的
from odps.models import Schema
myfunc = '''\
from odps.udf import annotate
from odps.distcache import get_cache_file
@annotate('bigint->bigint')
class Example(object):
def __init__(self):
self.n = int(get_cache_file('test_alias_res1').read())
def evaluate(self, arg):
return arg + self.n '''
res1 = o.create_resource('test_alias_res1', 'file', file_obj='1')
o.create_resource('test_alias.py', 'py', file_obj=myfunc)
o.create_function('test_alias_func',
class_type='test_alias.Example',
resources=['test_alias.py', 'test_alias_res1'])
table = o.create_table('test_table',
schema=Schema.from_lists(['size'], ['bigint']),
if_not_exists=True )
data = [[1, ], ] # 寫⼊⼀⾏數據,只包含⼀個值1。
o.write_table(table, 0, [table.new_record(it) for it in data])
with o.execute_sql('select test_alias_func(size) from test_table').open_reader() as reader:
print(reader[0][0]) res2 = o.create_resource('test_alias_res2', 'file', file_obj='2')
#把內容爲1的資源alias成內容爲2的資源,您不需要修改UDF或資源。
with o.execute_sql( 'select test_alias_func(size) from test_table',
aliases={'test_alias_res1': 'test_alias_res2'}).open_reader() as reader:
print(reader[0][0])
任務實例
#基本操作
for instance in odps.list_instances():
print(instance.id)
odps.exist_instance('20191122012156832guqtqmim') #判斷是否存在實例
odps.get_instance('20191122012156832guqtqmim') #獲取實例
#獲取Logview地址
instance = odps.run_sql('desc ods_orders')
print(instance.id,instance.get_logview_address())
instance = odps.get_instance(instance.id)
print(instance.get_logview_address())
#任務實例狀態
instance = odps.get_instance('20191122012156832guqtqmim')
print(instance.status)
一個instance的狀態可以是Running,Suspended或者Terminated
is_terminated方法返回是否已經執行完畢
is_successful方法返回是否正確地執行完畢
調⽤wait_for_completion⽅法會阻塞直到Instance執⾏完成。
wait_for_success⽅法同樣會阻塞,但如果最終任務執⾏失敗,會拋出相關異常。
#子任務操作
print (instance.get_task_names()) #任務名稱
print(instance.get_task_result('AnonymousSQLTask')) #任務結果
#獲取任務進度
#while not instance.is_terminated():
for task_name in instance.get_task_names():
print(instance.id,instance.get_task_progress(task_name).get_stage_progress_formatted_string())
time.sleep(5)
-------------------#資源
…省略
#文件
#表
-------------------#函數
…省略
#基本操作
#創建函數
#刪除函數
#更新函數