Skip to content

Instantly share code, notes, and snippets.

@nszceta
Last active September 9, 2022 23:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nszceta/d5a6c26f4cde8e7cf6c5a9fc4c080106 to your computer and use it in GitHub Desktop.
Save nszceta/d5a6c26f4cde8e7cf6c5a9fc4c080106 to your computer and use it in GitHub Desktop.
Load a random sequence of JSON or Python dict into Postgres as fast as possible
import sys
import json
import time
import psycopg2
import psycopg2.extras
psycopg2.extensions.register_adapter(dict, psycopg2.extras.Json)
def load(tablename, filepath):
with open(filepath) as fd:
records = json.load(fd)
insert_query = f"INSERT INTO {tablename} VALUES %s"
start_time = time.time()
with psycopg2.connect("postgresql://adam:@localhost/adam") as conn:
with conn.cursor() as curs:
psycopg2.extras.execute_values(
curs,
insert_query,
([r] for r in records),
template=None,
page_size=10_000,
)
print(f"{round(len(records) / (time.time() - start_time), 2)} requests per second")
if __name__ == "__main__":
_, tablename, filepath = sys.argv
load(tablename, filepath)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment