Skip to content

Python SDK topic reader without consumer docs #17064

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 29 additions & 2 deletions ydb/docs/en/core/reference/ydb-sdk/topic.md
Original file line number Diff line number Diff line change
Expand Up @@ -1184,7 +1184,8 @@ All the metadata provided when writing a message is sent to a consumer with the

### Connecting to a topic for message reads {#start-reader}

To be able to read messages from topic, a Consumer on this topic should exist.
Reading messages from a topic can be done by specifying a Consumer associated with that topic, as well as without a Consumer. If a Consumer is not specified, the client application must calculate the offset for reading messages on its own. A more detailed example of reading without a Consumer is discussed in the [relevant section](#no-consumer).

A Consumer can be created on [creating](#create-topic) or [altering](#alter-topic) a topic.
Topic can have several Consumers and for each of them server stores its own reading progress.

Expand Down Expand Up @@ -1222,7 +1223,7 @@ Topic can have several Consumers and for each of them server stores its own read
To establish a connection to the existing `my-topic` topic using the added `my-consumer` consumer, use the following code:

```python
reader = driver.topic_client.reader(topic="topic-path", consumer="consumer_name")
reader = driver.topic_client.reader(topic="my-topic", consumer="my-consumer")
```

- Java (sync)
Expand Down Expand Up @@ -1928,6 +1929,32 @@ Reading progress is usually saved on a server for each Consumer. However, such p
}
```

- Python

To read without a `Consumer`, create a reader using the `reader` method with specifying these arguments:
* `topic` - `ydb.TopicReaderSelector` object with defined `path` and `partitions` list;
* `consumer` - should be `None`;
* `event_handler` - inheritor of `ydb.TopicReaderEvents.EventHandler` that implements the `on_partition_get_start_offset` function. This function is responsible for returning the initial offset for reading messages when the reader starts and during reconnections. The client application must specify this offset in the parameter `ydb.TopicReaderEvents.OnPartitionGetStartOffsetResponse.start_offset`. The function can also be implemented as asynchronous.

Example:

```python
class CustomEventHandler(ydb.TopicReaderEvents.EventHandler):
def on_partition_get_start_offset(self, event: ydb.TopicReaderEvents.OnPartitionGetStartOffsetRequest):
return ydb.TopicReaderEvents.OnPartitionGetStartOffsetResponse(
start_offset=0,
)

reader = driver.topic_client.reader(
topic=ydb.TopicReaderSelector(
path="topic-path",
partitions=[0, 1, 2],
),
consumer=None,
event_handler=CustomEventHandler(),
)
```

{% endlist %}

### Reading in a transaction {#read-tx}
Expand Down
33 changes: 30 additions & 3 deletions ydb/docs/ru/core/reference/ydb-sdk/topic.md
Original file line number Diff line number Diff line change
Expand Up @@ -1182,7 +1182,8 @@

### Подключение к топику для чтения сообщений {#start-reader}

Для чтения сообщений из топика необходимо наличие заранее созданного Consumer, связанного с этим топиком.
Чтение сообщений из топика может выполнятся с указанием Consumer'а, связанного с этим топиком, а также без Consumer'а. Если Consumer не указан, то клиентское приложение должно самостоятельно рассчитывать offset для чтения сообщений. Более подробно пример чтения без Consumer'а рассмотрен в [соответствующей секции](#no-consumer).

Создать Consumer можно при [создании](#create-topic) или [изменении](#alter-topic) топика.
У топика может быть несколько Consumer'ов и для каждого из них сервер хранит свой прогресс чтения.

Expand Down Expand Up @@ -1220,7 +1221,7 @@
Чтобы создать подключение к существующему топику `my-topic` через добавленного ранее читателя `my-consumer`, используйте следующий код:

```python
reader = driver.topic_client.reader(topic="topic-path", consumer="consumer_name")
reader = driver.topic_client.reader(topic="my-topic", consumer="my-consumer")
```

- Java (sync)
Expand Down Expand Up @@ -1909,7 +1910,7 @@

- Java

Для чтения без `Consumer`а следует в настройках читателя `ReaderSettings` это явно указать, вызвав `withoutConsumer()`:
Для чтения без Consumer'а следует в настройках читателя `ReaderSettings` это явно указать, вызвав `withoutConsumer()`:

```java
ReaderSettings settings = ReaderSettings.newBuilder()
Expand All @@ -1931,6 +1932,32 @@
}
```

- Python

Для чтения без Consumer'а следует создать читателя с помощью метода `reader` с указанием следующих аргументов:
* `topic` - объект `ydb.TopicReaderSelector` с указанными `path` и списком `partitions`;
* `consumer` - должен быть `None`;
* `event_handler` - наследник `ydb.TopicReaderEvents.EventHandler`, который реализует функцию `on_partition_get_start_offset`. Эта функция отвечает за возвращение начального смещения (offset) для чтения сообщений при старте читателя, а также во время переподключений. Клиентское приложение должно указать это смещение в параметре `ydb.TopicReaderEvents.OnPartitionGetStartOffsetResponse.start_offset`. Также функция может быть реализована как асинхронная.

Пример:

```python
class CustomEventHandler(ydb.TopicReaderEvents.EventHandler):
def on_partition_get_start_offset(self, event: ydb.TopicReaderEvents.OnPartitionGetStartOffsetRequest):
return ydb.TopicReaderEvents.OnPartitionGetStartOffsetResponse(
start_offset=0,
)

reader = driver.topic_client.reader(
topic=ydb.TopicReaderSelector(
path="topic-path",
partitions=[0, 1, 2],
),
consumer=None,
event_handler=CustomEventHandler(),
)
```

{% endlist %}

### Чтение в транзакции {#read-tx}
Expand Down
Loading