|
| 1 | +from questdb.ingress import Sender |
| 2 | +import random |
| 3 | +import uuid |
| 4 | +import time |
| 5 | + |
| 6 | + |
| 7 | +def example(host: str = 'localhost', port: int = 9009): |
| 8 | + table_name: str = str(uuid.uuid1()) |
| 9 | + watermark = 1024 # Flush if the internal buffer exceeds 1KiB |
| 10 | + with Sender(host=host, port=port, auto_flush=watermark) as sender: |
| 11 | + total_rows = 0 |
| 12 | + last_flush = time.monotonic() |
| 13 | + try: |
| 14 | + print("Ctrl^C to terminate...") |
| 15 | + while True: |
| 16 | + time.sleep(random.randint(0, 750) / 1000) # sleep up to 750 ms |
| 17 | + |
| 18 | + print('Inserting row...') |
| 19 | + sender.row( |
| 20 | + table_name, |
| 21 | + symbols={ |
| 22 | + 'src': random.choice(('ALPHA', 'BETA', 'OMEGA')), |
| 23 | + 'dst': random.choice(('ALPHA', 'BETA', 'OMEGA'))}, |
| 24 | + columns={ |
| 25 | + 'price': random.randint(200, 500), |
| 26 | + 'qty': random.randint(1, 5)}) |
| 27 | + total_rows += 1 |
| 28 | + |
| 29 | + # If the internal buffer is empty, then auto-flush triggered. |
| 30 | + if len(sender) == 0: |
| 31 | + print('Auto-flush triggered.') |
| 32 | + last_flush = time.monotonic() |
| 33 | + |
| 34 | + # Flush at least once every five seconds. |
| 35 | + if time.monotonic() - last_flush > 5: |
| 36 | + print('Timer-flushing triggered.') |
| 37 | + sender.flush() |
| 38 | + last_flush = time.monotonic() |
| 39 | + |
| 40 | + except KeyboardInterrupt: |
| 41 | + print(f"table: {table_name}, total rows sent: {total_rows}") |
| 42 | + print("(wait commitLag for all rows to be available)") |
| 43 | + print("bye!") |
| 44 | + |
| 45 | + |
| 46 | +if __name__ == '__main__': |
| 47 | + example() |
0 commit comments