Skip to content

Commit f07df64

Browse files
committed
Add huge select example
1 parent 120ab80 commit f07df64

File tree

2 files changed

+110
-2
lines changed
  • ydb/docs

2 files changed

+110
-2
lines changed

ydb/docs/en/core/dev/example-app/python/index.md

Lines changed: 55 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -488,4 +488,58 @@ A code snippet demonstrating the explicit use of `transaction().begin()` and `tx
488488
{% endlist %}
489489

490490
However, it is worth remembering that a transaction can be opened implicitly at the first request. It could be commited automatically with the explicit indication of the `commit_tx=True` flag.
491-
Implicit transaction management is preferable because it requires fewer server calls.
491+
Implicit transaction management is preferable because it requires fewer server calls. An example of implicit control will be demonstrated in the next block.
492+
493+
## Huge Selects {#huge-selects}
494+
495+
To perform `SELECT` operations with an unlimited number of found rows, you must also use the `transaction().execute(query)` method. As mentioned above, the result of the work is an iterator - unlike `pool.execute_with_retries(query)`, it allows you to go through the selection without first loading it into memory.
496+
497+
Example of a `SELECT` with unlimited data and implicit transaction control:
498+
499+
{% list tabs %}
500+
501+
- Synchronous
502+
503+
```python
504+
def huge_select(pool: ydb.QuerySessionPool, path: str):
505+
def callee(session: ydb.QuerySessionSync):
506+
query = f"""
507+
PRAGMA TablePathPrefix("{path}");
508+
SELECT * from episodes;
509+
"""
510+
511+
with session.transaction().execute(
512+
query,
513+
commit_tx=True,
514+
) as result_sets:
515+
print("\n> Huge SELECT call")
516+
for result_set in result_sets:
517+
for row in result_set.rows:
518+
print("episode title:", row.title, ", air date:", row.air_date)
519+
520+
return pool.retry_operation_sync(callee)
521+
```
522+
523+
- Asynchronous
524+
525+
```python
526+
async def huge_select(pool: ydb.aio.QuerySessionPoolAsync, path: str):
527+
async def callee(session: ydb.aio.QuerySessionAsync):
528+
query = f"""
529+
PRAGMA TablePathPrefix("{path}");
530+
SELECT * from episodes;
531+
"""
532+
533+
async with await session.transaction().execute(
534+
query,
535+
commit_tx=True,
536+
) as result_sets:
537+
print("\n> Huge SELECT call")
538+
async for result_set in result_sets:
539+
for row in result_set.rows:
540+
print("episode title:", row.title, ", air date:", row.air_date)
541+
542+
return await pool.retry_operation_async(callee)
543+
```
544+
545+
{% endlist %}

ydb/docs/ru/core/dev/example-app/python/index.md

Lines changed: 55 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -489,4 +489,58 @@ series, Id: 1, title: IT Crowd, Release date: 2006-02-03
489489
{% endlist %}
490490

491491
Однако стоит помнить, что транзакция может быть открыта неявно при первом запросе. Завершиться же она может автоматически с явным указанием флага `commit_tx=True`.
492-
Неявное управление транзакцией предпочтительно, так как требует меньше обращений к серверу.
492+
Неявное управление транзакцией предпочтительно, так как требует меньше обращений к серверу. Пример неявного управления будет продемонстрирован в следующем блоке.
493+
494+
## Чтение неограниченной выборки {#huge-selects}
495+
496+
Для выполнения операций `SELECT` с неограниченным количеством найденных строк нужно также использовать метод `transaction().execute(query)`. Как было сказано выше, результатом работы является итератор - он, в отличие от `pool.execute_with_retries(query)`, позволяет пройтись по выборке не загружая ее предварительно в память.
497+
498+
Пример `SELECT` с неограниченным количеством данных и неявным контролем транзакции:
499+
500+
{% list tabs %}
501+
502+
- Синхронный
503+
504+
```python
505+
def huge_select(pool: ydb.QuerySessionPool, path: str):
506+
def callee(session: ydb.QuerySessionSync):
507+
query = f"""
508+
PRAGMA TablePathPrefix("{path}");
509+
SELECT * from episodes;
510+
"""
511+
512+
with session.transaction().execute(
513+
query,
514+
commit_tx=True,
515+
) as result_sets:
516+
print("\n> Huge SELECT call")
517+
for result_set in result_sets:
518+
for row in result_set.rows:
519+
print("episode title:", row.title, ", air date:", row.air_date)
520+
521+
return pool.retry_operation_sync(callee)
522+
```
523+
524+
- Асинхронный
525+
526+
```python
527+
async def huge_select(pool: ydb.aio.QuerySessionPoolAsync, path: str):
528+
async def callee(session: ydb.aio.QuerySessionAsync):
529+
query = f"""
530+
PRAGMA TablePathPrefix("{path}");
531+
SELECT * from episodes;
532+
"""
533+
534+
async with await session.transaction().execute(
535+
query,
536+
commit_tx=True,
537+
) as result_sets:
538+
print("\n> Huge SELECT call")
539+
async for result_set in result_sets:
540+
for row in result_set.rows:
541+
print("episode title:", row.title, ", air date:", row.air_date)
542+
543+
return await pool.retry_operation_async(callee)
544+
```
545+
546+
{% endlist %}

0 commit comments

Comments
 (0)