使用 Python 将迭代数据插入 Cassandra 的正确方法
Proper way to insert iterative data into Cassandra using Python
假设我有 cassandra table 定义如下:
CREATE TABLE IF NOT EXISTS {} (
user_id bigint ,
username text,
age int,
PRIMARY KEY (user_id)
);
我有 3 个相同大小的列表,让我们在每个列表中 1 000 000
记录。使用这样的 for 循环插入数据是一种好习惯吗:
for index, user_id in enumerate(user_ids):
query = "INSERT INTO TABLE (user_id, username, age) VALUES ({0}, '{1}', {1});".format(user_id, username[index] ,age[index])
session.execute(query)
首先查看 python 驱动程序获得 started guide 可能是个好主意。如果您已经看过,那么抱歉,但我认为值得一提。
一般来说,您会创建会话对象,然后在循环中执行插入,可能使用准备好的语句之类的东西(在入门页面的下方讨论过),但也 here and here
上面页面的例子以此为起点
user_lookup_stmt = session.prepare("SELECT * FROM users WHERE user_id=?")
users = []
for user_id in user_ids_to_query:
user = session.execute(user_lookup_stmt, [user_id])
users.append(user)
在讨论使用 python 驱动程序
提高吞吐量时,您可能还会发现 this blog 有帮助
您可能会找到对您也有帮助的 python driver github page a useful resource, in particular I found this example using a prepared statement here。
并发执行的准备好的语句将是您最好的选择。驱动程序提供实用函数,用于并发执行带有参数序列的语句,就像您使用列表一样:execute_concurrent_with_args
Zipping 您的列表将生成一系列适合该函数输入的参数元组。
像这样:
prepared = session.prepare("INSERT INTO table (user_id, username, age) VALUES (?, ?, ?)")
execute_concurrent_with_args(session, prepared, zip(user_ids, username, age))
假设我有 cassandra table 定义如下:
CREATE TABLE IF NOT EXISTS {} (
user_id bigint ,
username text,
age int,
PRIMARY KEY (user_id)
);
我有 3 个相同大小的列表,让我们在每个列表中 1 000 000
记录。使用这样的 for 循环插入数据是一种好习惯吗:
for index, user_id in enumerate(user_ids):
query = "INSERT INTO TABLE (user_id, username, age) VALUES ({0}, '{1}', {1});".format(user_id, username[index] ,age[index])
session.execute(query)
首先查看 python 驱动程序获得 started guide 可能是个好主意。如果您已经看过,那么抱歉,但我认为值得一提。
一般来说,您会创建会话对象,然后在循环中执行插入,可能使用准备好的语句之类的东西(在入门页面的下方讨论过),但也 here and here
上面页面的例子以此为起点
user_lookup_stmt = session.prepare("SELECT * FROM users WHERE user_id=?")
users = []
for user_id in user_ids_to_query:
user = session.execute(user_lookup_stmt, [user_id])
users.append(user)
在讨论使用 python 驱动程序
提高吞吐量时,您可能还会发现 this blog 有帮助您可能会找到对您也有帮助的 python driver github page a useful resource, in particular I found this example using a prepared statement here。
并发执行的准备好的语句将是您最好的选择。驱动程序提供实用函数,用于并发执行带有参数序列的语句,就像您使用列表一样:execute_concurrent_with_args
Zipping 您的列表将生成一系列适合该函数输入的参数元组。
像这样:
prepared = session.prepare("INSERT INTO table (user_id, username, age) VALUES (?, ?, ?)")
execute_concurrent_with_args(session, prepared, zip(user_ids, username, age))