python - 如何在 python 中使用单个进程扩展 psycopg2 插入和选择?

标签 python multithreading postgresql scalability psycopg2

我的插入平均需要大约 0.300095081329 才能完成提交到 postgres。

这是我的表格样式

id_table
    latest_update_id (primary index)
    product_id       (index)
    publish_date

product_meta_table
    latest_update_id    (index)
    product_id          (index)
    meta_related_info1
    meta_related_info2
    ...etc

product_table
    latest_update_id    (index)
    product_id          (index)
    note_related_info1
    note_related_info2
    ....etc

这是我的一些插页

db_cursor.execute("INSERT INTO id_table (product_id, publish_date)  \
             VALUES (%s, %s) RETURNING latest_update_id",
    (my_dict["product_id"], my_dict["publish_date"])
)

 db_cursor.execute("INSERT INTO product_table ( \
                   latest_update_id, \
                   product_id, \
                   note_related_info1, \
                   note_related_info2, \
                   ...etc)  \
             VALUES (%s, %s, %s, %s) RETURNING *",
    (my_dict["latest_update_id"], 
     my_dict["product_id"],
     my_dict["note_related_info1"],
     my_dict["note_related_info2"])
)       

使用插入时间我的吞吐量约为 1/0.3 = 3qps

我知道我可以通过添加更多实例来水平扩展它,但我想看看我是否至少可以达到 3000qps

我正在考虑使用 aync 或线程,但不确定 GIL 是否会干扰。

是否有关于如何使用 psycopg2 扩展 insert 语句的通用良好实践和技术?

谢谢

注意:我使用的是python 2.7

注意:python进程是通过https与sql server通信

注意:每个表的插入是交错的,table2插入在table1之后,table3插入在table2之后。从技术上讲,table2 和 table3 只需等待 table1 完成插入,因为它们需要 latest_update_id

最佳答案

执行单个插入查询而不是 3。注意三重引号和字典参数传递:

insert_query = """
    with i as (
        insert into id_table (product_id, publish_date) 
        values (%(product_id)s, %(publish_date)s)
        returning latest_update_id
    )
    insert into product_table (
        latest_update_id,
        product_id,
        note_related_info1,
        note_related_info2
    ) values (
        (select latest_update_id from i),
        %(product_id)s, %(note_related_info1)s, %(note_related_info2)s
    )
    returning *
"""

db_cursor.execute(insert_query, my_dict)

关于python - 如何在 python 中使用单个进程扩展 psycopg2 插入和选择?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46025675/

相关文章:

c++ - 使用 C++ 中的所有同步方法类

ruby-on-rails - SQL查询和ActiveRecord.find_by_sql返回不同的结果怎么可能?

java - 当要获取的字段作为 spring data jpa 中的请求的一部分出现时,我们如何以所需的格式获取 ResultSet?

django - 错误 : Please install the PostgreSQL server development packages and re-run configure

python - Django:测试加载静态文件是否成功

javascript - Csrf 验证失败 - Django Rest 和 Backbone.js

python - 为什么 uwsgi 找不到使用 --user 安装的 python 包?

python - 是否可以在 PyShark 中访问数据包的 hexdump?

c++ - 如何使用 pthreads 在 solaris 上增加 c++ 线程堆栈大小?

c++ - 传递给新线程的结构有错误的值