# Парсинг и сохранение в БД занимает ~10 секунд parse_text_and_save_to_postgres(text_data)
Asked at
AI answer
First, I would measure the time spent on each stage separately: parsing, data preparation, and writing to PostgreSQL. time.perf_counter() and a profiler are suitable for this; optimizing without measurements is risky.
If writing is the bottleneck, it usually helps to avoid executing an INSERT for each record individually: prepare the rows and insert them in batches within a single transaction. For large volumes of data, COPY is often more efficient in PostgreSQL. It is also worth checking the query plan and indexes, but don’t add indexes blindly: they speed up reads but slow down writes.
import time
start = time.perf_counter()
rows = parse(text_data)
parsed_at = time.perf_counter()
with conn.cursor() as cur:
cur.executemany(
"INSERT INTO records (field_a, field_b) VALUES (%s, %s)",
[(row.field_a, row.field_b) for row in rows],
)
conn.commit()
print(f"parse={parsed_at - start:.2f}s, save={time.perf_counter() - parsed_at:.2f}s")
If parsing itself is slow, profile it separately and optimize the most expensive operations. After making changes, compare the time using the same amount of data and verify that the results are correct.
Also asked at GigaChat / Сбер
- app = FastAPI() def get_db(): db = SessionLocal() try: yield db finally: db.close() def heavy_text_parser(file_id: int, db: Session): # Parsing a file that takes 5 minutes parse_and_save(file_id, db) @app.post("/upload") async def upload_file( background_tasks: BackgroundTasks, db: Session = Depends(get_db) ): file_id = save_file_to_db(db) db.commit() background_tasks.add_task(heavy_text_parser, file_id, db) return {"status": "parsing started"}
- def extract_emails_from_huge_file(file_path: str) -> list[str]: with open(file_path, 'r', encoding='utf-8') as f: content = f.read() # Заменяем переносы строк, чтобы текст был "сплошным" content = content.replace('\r\n', ' ').replace('\n', ' ') lines = content.split(' ') emails = [word for word in lines if '@' in word] return emails
Similar questions
- How would you save data to a database after parsing?
- broker = KafkaBroker("localhost:9092") app = FastStream(broker) @broker.subscriber("raw_texts_topic", group_id="text_parsers") async def handle_text(text_data: dict): # Парсинг и сохранение в БД занимает ~10 секунд parse_text_and_save_to_postgres(text_data)
- How can you connect and use a database within a Telegram bot to store and retrieve information?
- How can you find and analyze slow queries in PostgreSQL?
- import psycopg2 def save_prediction(text: str, result: str): conn = psycopg2.connect("host=db user=app password=secret dbname=ml") cur = conn.cursor() cur.execute( "INSERT INTO predictions (input, output) VALUES (%s, %s)", (text, result) ) conn.commit() cur.close()