表格存储 Python SDK 开发入门

本文涉及的产品
表格存储 Tablestore,50G 2个月
简介: 本文将结合电商订单场景为例,介绍表格存储 Tablestore Python SDK 的基本使用方法。

准备工作

在您开始Tablestore SDK开发前,需确保已开通表格存储服务并且已创建表格存储实例。

您需要提前获取到以下几个参数


开发简介

开发示例中将以订单场景为例,使用Tablestore SDK实现如下几个功能。

  • 订单表创建。
  • 订单插入。
  • 订单号查询。
  • 订单搜索。


字段名

字段类型

字段描述

order_id

String

主键

订单号

customer_name

String

属性列

消费者姓名

product_name

String

属性列

产品名

product_type

String

属性列

产品类型

order_time

String

属性列

下单时间

pay_time

String

属性列

支付时间

订单表

开发步骤

初始化连接

Tablestore支持Http/Https协议访问服务端,使用Python SDK发起请求前,您需要初始化一个OTSClinet实例,初始化需要获取到服务地址(endpoint)、实例名(instanceName)、密钥(accessKeyId、accessSecret)等信息。代码如下

if__name__=='__main__':
client=OTSClient("https://order-instance.cn-beijing.ots.aliyuncs.com",# your endpoint"",# your accessKeyId"",# your accessSecret"order-instance")#your insntace name#operation_method(client)

创建数据表

示例代码中创建了一张订单数据表order。

# 创建数据表defcreateOrderTable(client):
schema_of_primary_key= [('order_id', 'STRING')]
table_meta=TableMeta("order", schema_of_primary_key)
# 设置表数据生命周期为永久,设置表最大版本数为1table_option=TableOptions(-1, 1)
# 默认设置表预留读写cu为0reserved_throughput=ReservedThroughput(CapacityUnit(0, 0))
# 发送创建数据表请求client.create_table(table_meta, table_option, reserved_throughput)
print ('Table has been created.')

写入数据

示例代码中写入了一条订单数据,订单号order_id为“o1”。样例中模拟了一万条订单数据,这里不作展示。

defputOrder(client):
primary_key= [('order_id', 'o1')]
attribute_columns= [('customer_name', '消十一'),('product_name', 'iphone 6'),('product_type', '手机'),('order_time', '2021-10-25 09:20:01'),('pay_time', '2017-10-25 10:00:01')]
table_name='order'row=Row(primary_key, attribute_columns)
condition=Condition(RowExistenceExpectation.IGNORE)
consumed, return_row=client.put_row(table_name, row, condition)
print (u'Write succeed, consume %s write cu.'%consumed.write)

查询数据

示例代码中查询订单号order_id为“o1”的记录

defgetOrder(client):
primary_key= [('order_id', 'o1')]
columns_to_get= ['customer_name','product_name','product_type','order_time','pay_time']
table_name="order"consumed, return_row, next_token=client.get_row(table_name, primary_key, columns_to_get, None, 1)
print ('Value of primary key: %s'%return_row.primary_key)
print ('Value of attribute: %s'%return_row.attribute_columns)

创建多元索引

示例代码中创建了一个多元索引order_index。分别设置customer_name字符串类型、order_time字符串类型、pay_time字符串类型、product_name分词类型、product_type字符串类型。关于索引字段类型的介绍请参考多元索引概述

defcreateSearchIndex(client):
field_a=FieldSchema('customer_name', FieldType.KEYWORD, index=True, enable_sort_and_agg=True, store=True)
field_b=FieldSchema('order_time', FieldType.KEYWORD, index=True, enable_sort_and_agg=True, store=True)
field_c=FieldSchema('pay_time', FieldType.KEYWORD, index=True, enable_sort_and_agg=True, store=True)
field_d=FieldSchema('product_type', FieldType.TEXT, index=True, store=True, analyzer=AnalyzerType.SINGLEWORD)
field_e=FieldSchema('customer_name', FieldType.KEYWORD, index=True, enable_sort_and_agg=True, store=True)
fields= [field_a, field_b, field_c, field_d, field_e]
index_meta=SearchIndexMeta(fields, None, None)
client.create_search_index("order", "order_index", index_meta)
print ('create search index succeed')

搜索数据

示例代码中查询产品类型为“手机”的订单,并统计了符合条件的行数。

defsearchQuery1():
query=TermQuery('product_type', '手机')
search_response=client.search(
"order", "order_index",
SearchQuery(query, limit=100, get_total_count=True),
ColumnsToGet(return_type=ColumnReturnType.ALL)
    )

示例代码中搜索产品名包含“iphone”的订单,并统计了符合条件的行数。

defsearchQuery2():
query=MatchQuery('product_name', 'iphone')
search_response=client.search(
"order", "order_index",
SearchQuery(query, limit=100, get_total_count=True),
ColumnsToGet(return_type=ColumnReturnType.ALL)
        )

示例代码中查询了消费者姓名为“消十一”并且下单时间在“2021-10-24 00:00:00”之间的订单。并统计了行数。

defsearchQuery3():
bool_query=BoolQuery(
must_queries=[
TermQuery('customer_name', '消十一'),
RangeQuery('order_time', range_to='2021-10-24 00:00:00', include_upper=False)
        ]
    )
search_response=client.search(
"order", "order_index",
SearchQuery(
bool_query,
None,
limit=10,
get_total_count=True),
ColumnsToGet(return_type=ColumnReturnType.ALL)
    )

删除多元索引

示例代码中展示了删除订单表order中的order_index多元索引。

defdelete_search_index(index_name):
client.delete_search_index("order", "order_index")

删除数据表

示例代码中展示了删除订单表order。删除表之前需确保先删除表中的多元索引。

defdelete_table():
client.delete_table("order")

更多关于Tablestore Python SDK的介绍请参考Tablestore Python SDK

相关实践学习
阿里云表格存储使用教程
表格存储(Table Store)是构建在阿里云飞天分布式系统之上的分布式NoSQL数据存储服务,根据99.99%的高可用以及11个9的数据可靠性的标准设计。表格存储通过数据分片和负载均衡技术,实现数据规模与访问并发上的无缝扩展,提供海量结构化数据的存储和实时访问。 产品详情:https://www.aliyun.com/product/ots
目录
相关文章
|
1月前
|
SQL 关系型数据库 数据库
Python SQLAlchemy模块:从入门到实战的数据库操作指南
免费提供Python+PyCharm编程环境,结合SQLAlchemy ORM框架详解数据库开发。涵盖连接配置、模型定义、CRUD操作、事务控制及Alembic迁移工具,以电商订单系统为例,深入讲解高并发场景下的性能优化与最佳实践,助你高效构建数据驱动应用。
285 7
|
1月前
|
搜索推荐 API 开发工具
百宝箱开放平台 ✖️ Python SDK
百宝箱提供Python SDK,支持开发者集成其开放能力。需先发布应用,安装Python 3.6+环境后,通过pip安装tboxsdk,即可调用对话型、生成型智能体及文件上传等功能。
706 87
百宝箱开放平台 ✖️  Python SDK
|
2月前
|
测试技术 开发者 Python
Python单元测试入门:3个核心断言方法,帮你快速定位代码bug
本文介绍Python单元测试基础,详解`unittest`框架中的三大核心断言方法:`assertEqual`验证值相等,`assertTrue`和`assertFalse`判断条件真假。通过实例演示其用法,帮助开发者自动化检测代码逻辑,提升测试效率与可靠性。
320 1
|
1月前
|
Cloud Native 算法 API
Python API接口实战指南:从入门到精通
🌟蒋星熠Jaxonic,技术宇宙的星际旅人。深耕API开发,以Python为舟,探索RESTful、GraphQL等接口奥秘。擅长requests、aiohttp实战,专注性能优化与架构设计,用代码连接万物,谱写极客诗篇。
Python API接口实战指南:从入门到精通
|
2月前
|
开发工具 Android开发
X Android SDK file not found: adb.安卓开发常见问题-Android SDK 缺少 `adb`(Android Debug Bridge)-优雅草卓伊凡
X Android SDK file not found: adb.安卓开发常见问题-Android SDK 缺少 `adb`(Android Debug Bridge)-优雅草卓伊凡
492 11
X Android SDK file not found: adb.安卓开发常见问题-Android SDK 缺少 `adb`(Android Debug Bridge)-优雅草卓伊凡
|
1月前
|
存储 Java 调度
Python定时任务实战:APScheduler从入门到精通
APScheduler是Python强大的定时任务框架,通过触发器、执行器、任务存储和调度器四大组件,灵活实现各类周期性任务。支持内存、数据库、Redis等持久化存储,适用于Web集成、数据抓取、邮件发送等场景,解决传统sleep循环的诸多缺陷,助力构建稳定可靠的自动化系统。(238字)
472 1
|
2月前
|
设计模式 人工智能 API
AI智能体开发实战:17种核心架构模式详解与Python代码实现
本文系统解析17种智能体架构设计模式,涵盖多智能体协作、思维树、反思优化与工具调用等核心范式,结合LangChain与LangGraph实现代码工作流,并通过真实案例验证效果,助力构建高效AI系统。
423 7
|
2月前
|
调度 数据库 Python
Python异步编程入门:asyncio让并发变得更简单
Python异步编程入门:asyncio让并发变得更简单
180 5
|
2月前
|
数据采集 存储 XML
Python爬虫入门(1)
在互联网时代,数据成为宝贵资源,Python凭借简洁语法和丰富库支持,成为编写网络爬虫的首选。本文介绍Python爬虫基础,涵盖请求发送、内容解析、数据存储等核心环节,并提供环境配置及实战示例,助你快速入门并掌握数据抓取技巧。
|
9月前
|
前端开发 Java Shell
【08】flutter完成屏幕适配-重建Android,增加GetX路由,屏幕适配,基础导航栏-多版本SDK以及gradle造成的关于fvm的使用(flutter version manage)-卓伊凡换人优雅草Alex-开发完整的社交APP-前端客户端开发+数据联调|以优雅草商业项目为例做开发-flutter开发-全流程-商业应用级实战开发-优雅草Alex
【08】flutter完成屏幕适配-重建Android,增加GetX路由,屏幕适配,基础导航栏-多版本SDK以及gradle造成的关于fvm的使用(flutter version manage)-卓伊凡换人优雅草Alex-开发完整的社交APP-前端客户端开发+数据联调|以优雅草商业项目为例做开发-flutter开发-全流程-商业应用级实战开发-优雅草Alex
630 20
【08】flutter完成屏幕适配-重建Android,增加GetX路由,屏幕适配,基础导航栏-多版本SDK以及gradle造成的关于fvm的使用(flutter version manage)-卓伊凡换人优雅草Alex-开发完整的社交APP-前端客户端开发+数据联调|以优雅草商业项目为例做开发-flutter开发-全流程-商业应用级实战开发-优雅草Alex

推荐镜像

更多