--- sidebar_label: Subscription title: Data Subscritpion description: Use data subscription to get data from TDengine. --- import Tabs from "@theme/Tabs"; import TabItem from "@theme/TabItem"; import Java from "./_sub_java.mdx"; import Python from "./_sub_python.mdx"; import Go from "./_sub_go.mdx"; import Node from "./_sub_node.mdx"; import CSharp from "./_sub_cs.mdx"; import CDemo from "./_sub_c.mdx"; This topic introduces how to read out data from TDengine using data subscription, which is an advanced feature in TDengine. To access the data in TDengine in data subscription way, you need to create topic, create consumer, subscribe to a topic, and consume data. In this document we will briefly explain these main steps of data subscription. ## Create Topic A topic can be created on a database, on some selected columns,or on a supertable. ### Topic on Columns The most common way to create a topic is to create a topic on some specifically selected columns. The Syntax is like below: ```sql CREATE TOPIC topic_name as subquery; ``` You can subscribe to a topic through a SELECT statement. Statements that specify columns, such as `SELECT *` and `SELECT ts, cl` are supported, as are filtering conditions and scalar functions. Aggregate functions and time window aggregation are not supported. Note: - The schema of topics created in this manner is determined by the subscribed data. - You cannot modify (`ALTER MODIFY`) or delete (`ALTER
DROP`) columns or tags that are used in a subscription or calculation. - Columns added to a table after the subscription is created are not displayed in the results. Deleting columns will cause an error. For example: ```sql CREATE TOPIC topic_name AS SELECT ts, c1, c2, c3 FROM tmqdb.stb WHERE c1 > 1; ``` ### Topic on SuperTable Syntax: ```sql CREATE TOPIC topic_name AS STABLE stb_name; ``` Creating a topic in this manner differs from a `SELECT * from stbName` statement as follows: - The table schema can be modified. - Unstructured data is returned. The format of the data returned changes based on the supertable schema. - A different table schema may exist for every data block to be processed. - The data returned does not include tags. ### Topic on Database Syntax: ```sql CREATE TOPIC topic_name [WITH META] AS DATABASE db_name; ``` This SQL statement creates a subscription to all tables in the database. You can add the `WITH META` parameter to include schema changes in the subscription, including creating and deleting supertables; adding, deleting, and modifying columns; and creating, deleting, and modifying the tags of subtables. Consumers can determine the message type from the API. Note that this differs from Kafka. ## Create Consumer To create a consumer, you must use the APIs provided by TDengine connectors. Below is the sample code of using connectors of different languages. You configure the following parameters when creating a consumer: | Parameter | Type | Description | Remarks | | :----------------------------: | :-----: | -------------------------------------------------------- | ------------------------------------------- | | `td.connect.ip` | string | Used in establishing a connection; same as `taos_connect` | | | `td.connect.user` | string | Used in establishing a connection; same as `taos_connect` | | | `td.connect.pass` | string | Used in establishing a connection; same as `taos_connect` | | | `td.connect.port` | string | Used in establishing a connection; same as `taos_connect` | | | `group.id` | string | Consumer group ID; consumers with the same ID are in the same group | **Required**. Maximum length: 192. | | `client.id` | string | Client ID | Maximum length: 192. | | `auto.offset.reset` | enum | Initial offset for the consumer group | Specify `earliest`, `latest`, or `none`(default) | | `enable.auto.commit` | boolean | Commit automatically | Specify `true` or `false`. | | `auto.commit.interval.ms` | integer | Interval for automatic commits, in milliseconds | | `enable.heartbeat.background` | boolean | Backend heartbeat; if enabled, the consumer does not go offline even if it has not polled for a long time | | | `experimental.snapshot.enable` | boolean | Specify whether to consume messages from the WAL or from TSBS | | | `msg.with.table.name` | boolean | Specify whether to deserialize table names from messages | The method of specifying these parameters depends on the language used: Will be available soon Will be available soon Will be available soon ```rust let mut dsn = std::env::var("TDENGINE_CLOUD_DSN").parse()?; dsn.set("group.id", "group1"); dsn.set("client.id", "test"); dsn.set("auto.offset.reset", "earliest"); let tmq = TmqBuilder::from_dsn(dsn)?; let mut consumer = tmq.build()?; ``` Will be available soon Will be available soon Will be available soon A consumer group is automatically created when multiple consumers are configured with the same consumer group ID. ## Subscribe to a Topic A single consumer can subscribe to multiple topics. Will be available soon Will be available soon Will be available soon ```rust consumer.subscribe(["tmq_meters"]).await?; ``` Will be available soon Will be available soon Will be available soon ## Consume messages The following code demonstrates how to consume the messages in a queue. Will be available soon Will be available soon Will be available soon ```rust { let mut stream = consumer.stream(); while let Some((offset, message)) = stream.try_next().await? { // get information from offset // the topic let topic = offset.topic(); // the vgroup id, like partition id in kafka. let vgroup_id = offset.vgroup_id(); println!("* in vgroup id {vgroup_id} of topic {topic}\n"); if let Some(data) = message.into_data() { while let Some(block) = data.fetch_raw_block().await? { // one block for one table, get table name if needed let name = block.table_name(); let records: Vec = block.deserialize().try_collect()?; println!( "** table: {}, got {} records: {:#?}\n", name.unwrap(), records.len(), records ); } } consumer.commit(offset).await?; } } ``` Will be available soon Will be available soon Will be available soon ## Subscribe to a Topic A single consumer can subscribe to multiple topics. Will be available soon Will be available soon Will be available soon ```rust consumer.subscribe(["tmq_meters"]).await?; ``` Will be available soon Will be available soon Will be available soon ## Consume Data The following code demonstrates how to consume the messages in a queue. Will be available soon The `while` loop obtains a message each time it calls `tmq_consumer_poll()`. This message is exactly the same as the result returned by a query, and the same deserialization API can be used on it. Will be available soon Will be available soon ```rust { let mut stream = consumer.stream(); while let Some((offset, message)) = stream.try_next().await? { // get information from offset // the topic let topic = offset.topic(); // the vgroup id, like partition id in kafka. let vgroup_id = offset.vgroup_id(); println!("* in vgroup id {vgroup_id} of topic {topic}\n"); if let Some(data) = message.into_data() { while let Some(block) = data.fetch_raw_block().await? { // one block for one table, get table name if needed let name = block.table_name(); let records: Vec = block.deserialize().try_collect()?; println!( "** table: {}, got {} records: {:#?}\n", name.unwrap(), records.len(), records ); } } consumer.commit(offset).await?; } } ``` Will be available soon Will be available soon Will be available soon ## Close the consumer After message consumption is finished, the consumer is unsubscribed. Will be available soon Will be available soon Will be available soon ```rust consumer.unsubscribe().await; ``` Will be available soon Will be available soon Will be available soon ## Close Consumer After message consumption is finished, the consumer is unsubscribed. Will be available soon Will be available soon Will be available soon ```rust consumer.unsubscribe().await; ``` Will be available soon Will be available soon Will be available soon ## Delete Topic Once a topic becomes useless, it can be deleted. You can delete topics that are no longer useful. Note that you must unsubscribe all consumers from a topic before deleting it. ```sql /* Delete topic/ DROP TOPIC topic_name; ``` ## Check Status At any time, you can check the status of existing topics and consumers. 1. Query all existing topics. ```sql SHOW TOPICS; ``` 2. Query the status and subscribed topics of all consumers. ```sql SHOW CONSUMERS; ```