You are viewing a plain text version of this content. The canonical link for it is here.
Posted to reviews@iotdb.apache.org by "xiangmy21 (via GitHub)" <gi...@apache.org> on 2026/01/22 15:32:48 UTC

[PR] feat: show timeseries [order by timseries] clause [iotdb]

xiangmy21 opened a new pull request, #17065:
URL: https://github.com/apache/iotdb/pull/17065

   # feat: show timeseries [order by timseries] clause
   
   Support `ORDER BY TIMESERIES` in `SHOW TIMESERIES` and Optimize `OFFSET` with Subtree Measurement Statistics
   
   ---
   
   ## Brief
   
   This PR introduces ordering support for `SHOW TIMESERIES` by measurement name (lexicographical) and optimizes the performance of the `OFFSET` clause using subtree measurement statistics.
   
   Currently, `SHOW TIMESERIES` supports the `ORDER BY TIMESERIES` clause.
   When the query scope is within a single database, `OFFSET X` no longer requires traversing the first X measurements one by one. Instead, it skips subtrees in the metadata tree based on subtree measurement counts.
   
   Example:
   
   ```sql
   IoTDB> show timeseries root.dbtest.** order by timeseries desc limit 5 offset 5001
   +--------------------------------+-----+-----------+--------+--------+-----------+----+----------+--------+------------------+--------+
   |                      Timeseries|Alias|   Database|DataType|Encoding|Compression|Tags|Attributes|Deadband|DeadbandParameters|ViewType|
   +--------------------------------+-----+-----------+--------+--------+-----------+----+----------+--------+------------------+--------+
   |root.dbtest.plant9.device84.m188| null|root.dbtest|   INT32|     RLE|     SNAPPY|null|      null|    null|              null|    BASE|
   |root.dbtest.plant9.device84.m187| null|root.dbtest|   INT32|     RLE|     SNAPPY|null|      null|    null|              null|    BASE|
   |root.dbtest.plant9.device84.m186| null|root.dbtest|   INT32|     RLE|     SNAPPY|null|      null|    null|              null|    BASE|
   |root.dbtest.plant9.device84.m185| null|root.dbtest|   INT32|     RLE|     SNAPPY|null|      null|    null|              null|    BASE|
   |root.dbtest.plant9.device84.m184| null|root.dbtest|   INT32|     RLE|     SNAPPY|null|      null|    null|              null|    BASE|
   +--------------------------------+-----+-----------+--------+--------+-----------+----+----------+--------+------------------+--------+
   ```
   
   * `DESC`: descending order
   * `ASC`: ascending order (default if not specified)
   
   ---
   
   ## Design & Implementation Details
   
   ### 1. Syntax Extension
   
   * Updated the grammar of `SHOW TIMESERIES` to support `orderByTimeseriesClause`.
   * Added ordering-related fields to `ShowTimeSeriesStatement` to record sorting requirements.
   
   ### 2. Logical Plan Construction
   
   * Introduced a `SortNode` at the top of the logical plan to enable global ordering across partitions.
   * For single-partition queries, `LIMIT` and `OFFSET` are pushed down to the metadata tree traversal stage in `LogicalPlanVisitor`.
   
   ### 3. Limit/Offset Handling in Multi-Partition Queries
   
   * For multi-partition queries, `OFFSET` cannot be pushed down.
     Instead, `limit' = limit + offset` is used.
   * Fixed a bug in the previous implementation:
     when `limit = 0` (which is treated as unlimited in IoTDB), `limit'` was incorrectly pushed down, causing unexpected truncation of results.
   
   ### 4. Ordered Traversal in Metadata Tree
   
   * In `MTreeBelowSGMemoryImpl`, the iteration strategy of child nodes in `schemaReader` is overridden under ordering mode.
   * Child nodes are traversed in lexicographical order by name.
   
   ### 5. Subtree Measurement Count
   
   * Implemented subtree measurement statistics (only for in-memory metadata tree):
   
     * Added `subtreeMeasurementCount` to `IMemMNode` and related classes.
     * Maintained `subtreeMeasurementCount` along ancestor paths during measurement insertion and deletion.
     * This value is not persisted; it is initialized via a DFS during metadata tree loading.
   * During schemaReader construction, `acceptFullMatchedNode` is overridden to skip subtree traversal when `subtreeMeasurementCount < offset`.
   
   ---
   
   ## Tests
   
   ### Functional Tests
   * Added `IoTDBShowTimeseriesOrderByTimeseriesIT` to verify correctness of ordering and offset behavior.
   ### Performance Evaluation
   
   * Evaluated performance on a single-partition dataset with a typical three-level hierarchy:
     ```
     root.plantA.deviceB.measurementC
     ```
     with approximately 900,000 measurements.
   * Query pattern:
     ```sql
     SHOW TIMESERIES root.dbtest.** order by timeseries LIMIT 100 OFFSET X;
     ```
     where `X` ranges from 0 to 900,000 with a step of 5,000.
   * Compared the original implementation and the optimized version.
   * Results are shown in the figure below: 
   <img width="1200" height="800" alt="image" src="https://github.com/user-attachments/assets/625a2825-7790-4c95-9cb4-854c3307e7fb" />
   
   * Detailed benchmark methodology and results are available at: [[link].](https://apache-iotdb-project.feishu.cn/wiki/P0RcwbUleipgDjkKwhqcOkkynJd?from=from_copylink)
   
   ---
   
   ## Impact
   
   * Enables deterministic ordering for `SHOW TIMESERIES`.
   * Significantly reduces traversal cost for large `OFFSET` values in single-partition scenarios $O(limit+offset)\to O(limit+TreeHeight)$.
   * Improves correctness of limit/offset handling in multi-partition queries.
   * Introduces minimal overhead to metadata maintenance (in-memory only).
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@iotdb.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat: show timeseries [order by timseries] clause [iotdb]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #17065:
URL: https://github.com/apache/iotdb/pull/17065#discussion_r2727086526


##########
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/schemaengine/schemaregion/mtree/impl/mem/MTreeBelowSGMemoryImpl.java:
##########
@@ -192,6 +193,22 @@ public synchronized boolean createSnapshot(final File snapshotDir) {
     return store.createSnapshot(snapshotDir);
   }
 
+  private void applySubtreeMeasurementDelta(IMemMNode startNode, final long delta) {
+    if (delta == 0 || startNode == null) {
+      return;
+    }
+    IMemMNode current = startNode;
+    while (current != null) {
+      current.setSubtreeMeasurementCount(current.getSubtreeMeasurementCount() + delta);
+      current = current.getParent();
+    }
+  }
+
+  private long getTemplateMeasurementCount(final int templateId) {
+    final Template template = ClusterTemplateManager.getInstance().getTemplate(templateId);
+    return template == null ? 0L : template.getMeasurementNumber();

Review Comment:
   subtreeMeasurementCount is adjusted on template activation/deactivation using the current template measurement count (getTemplateMeasurementCount). Since templates can be extended at runtime (see ClusterSchemaManager.extendSchemaTemplate), the measurement count can change after activation; later deactivation will subtract a different value than was added, and the cached subtree counts can become stale or even negative. This can break OFFSET pruning correctness. Consider recording the activated template measurement count per device (so add/subtract are consistent), and/or updating subtreeMeasurementCount for all affected paths when a template is extended, or skipping subtree-count pruning for nodes affected by templates.
   ```suggestion
       // NOTE:
       // Templates can be extended at runtime, which changes their measurement count.
       // Using the current measurement count here for both activation and deactivation
       // can cause inconsistent deltas on subtreeMeasurementCount (e.g., subtracting
       // more/less than was previously added), leading to stale or even negative
       // subtree counts and incorrect OFFSET pruning.
       //
       // To avoid this correctness issue without per-device activation-time tracking,
       // we deliberately do *not* adjust subtreeMeasurementCount based on template
       // measurements and return 0 here. This effectively disables subtree-count
       // pruning for template-driven paths but preserves correctness.
       return 0L;
   ```



##########
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/schemaengine/schemaregion/mtree/impl/mem/MTreeBelowSGMemoryImpl.java:
##########
@@ -1123,6 +1150,23 @@ public long countPathsUsingTemplate(final PartialPath pathPattern, final int tem
     }
   }
 
+  public void rebuildSubtreeMeasurementCount() {
+    rebuildSubtreeMeasurementCountFromNode(rootNode);
+  }
+
+  private long rebuildSubtreeMeasurementCountFromNode(final IMemMNode node) {
+    long count = node.isMeasurement() ? 1L : 0L;
+    final IMNodeIterator<IMemMNode> iterator = store.getChildrenIterator(node);
+    while (iterator.hasNext()) {
+      count += rebuildSubtreeMeasurementCountFromNode(iterator.next());

Review Comment:
   rebuildSubtreeMeasurementCountFromNode() obtains an IMNodeIterator from store.getChildrenIterator(node) but never calls iterator.close(). Today the in-memory iterator close is mostly a no-op, but other IMNodeIterator implementations can hold resources; closing in a finally block would make this method safer and consistent with other iterator usages.
   ```suggestion
       try {
         while (iterator.hasNext()) {
           count += rebuildSubtreeMeasurementCountFromNode(iterator.next());
         }
       } finally {
         iterator.close();
   ```



##########
integration-test/src/test/java/org/apache/iotdb/db/it/schema/IoTDBShowTimeseriesOrderByTimeseriesIT.java:
##########
@@ -0,0 +1,221 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iotdb.db.it.schema;
+
+import org.apache.iotdb.commons.schema.column.ColumnHeaderConstant;
+import org.apache.iotdb.it.env.EnvFactory;
+import org.apache.iotdb.itbase.category.ClusterIT;
+import org.apache.iotdb.itbase.category.LocalStandaloneIT;
+import org.apache.iotdb.util.AbstractSchemaIT;
+
+import org.junit.After;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+import org.junit.runners.Parameterized;
+
+import java.sql.Connection;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+@Category({LocalStandaloneIT.class, ClusterIT.class})
+public class IoTDBShowTimeseriesOrderByTimeseriesIT extends AbstractSchemaIT {
+
+  private static final List<String> BASE_TIMESERIES =
+      Arrays.asList(
+          "root.db1.devA.m1",
+          "root.db1.devA.m2",
+          "root.db1.devB.m1",
+          "root.db1.devB.x",
+          "root.db2.devA.m1",
+          "root.db2.devC.m0",
+          "root.db2.devC.m3",
+          "root.db3.z.m1",
+          "root.db3.z.m10",
+          "root.db3.z.m2");
+
+  public IoTDBShowTimeseriesOrderByTimeseriesIT(SchemaTestMode schemaTestMode) {
+    super(schemaTestMode);
+  }
+
+  @Parameterized.BeforeParam
+  public static void before() throws Exception {
+    setUpEnvironment();
+    EnvFactory.getEnv().initClusterEnvironment();
+  }
+
+  @Parameterized.AfterParam
+  public static void after() throws Exception {
+    EnvFactory.getEnv().cleanClusterEnvironment();
+    tearDownEnvironment();
+  }
+
+  @After
+  public void tearDown() throws Exception {
+    clearSchema();
+  }
+
+  private void prepareComplexSchema() throws Exception {
+    try (Connection connection = EnvFactory.getEnv().getConnection();
+        Statement statement = connection.createStatement()) {
+      statement.execute("CREATE DATABASE root.db1");
+      statement.execute("CREATE DATABASE root.db2");
+      statement.execute("CREATE DATABASE root.db3");
+
+      for (String ts : BASE_TIMESERIES) {
+        statement.execute(
+            String.format(
+                "create timeseries %s with datatype=INT32, encoding=RLE, compression=SNAPPY", ts));
+      }
+    }
+  }
+
+  private List<String> queryTimeseries(final String sql) throws Exception {
+    try (Connection connection = EnvFactory.getEnv().getConnection();
+        Statement statement = connection.createStatement();
+        ResultSet resultSet = statement.executeQuery(sql)) {
+      List<String> result = new ArrayList<>();
+      while (resultSet.next()) {
+        result.add(resultSet.getString(ColumnHeaderConstant.TIMESERIES));
+      }
+      return result;
+    }
+  }
+
+  @Test
+  public void testOrderAscWithoutLimit() throws Exception {
+    prepareComplexSchema();
+    List<String> expected = new ArrayList<>(BASE_TIMESERIES);
+    Collections.sort(expected);
+
+    List<String> actual = queryTimeseries("show timeseries root.db*.** order by timeseries");
+    assertEquals(expected, actual);
+  }
+
+  @Test
+  public void testOrderDescWithOffsetLimit() throws Exception {
+    prepareComplexSchema();
+    List<String> expected = new ArrayList<>(BASE_TIMESERIES);
+    Collections.sort(expected);
+    Collections.reverse(expected);
+    expected = expected.subList(2, 6); // offset 2 limit 4
+
+    List<String> actual =
+        queryTimeseries("show timeseries root.db*.** order by timeseries desc offset 2 limit 4");
+    assertEquals(expected, actual);
+  }
+
+  @Test
+  public void testInsertThenQueryOrder() throws Exception {
+    prepareComplexSchema();
+    try (Connection connection = EnvFactory.getEnv().getConnection();
+        Statement statement = connection.createStatement()) {
+      statement.execute(
+          "create timeseries root.db0.devX.a with datatype=INT32, encoding=RLE, compression=SNAPPY");
+    }
+
+    List<String> expected = new ArrayList<>(BASE_TIMESERIES);
+    expected.add("root.db0.devX.a");
+    Collections.sort(expected);
+
+    List<String> actual = queryTimeseries("show timeseries root.db*.** order by timeseries");
+    assertEquals(expected, actual);
+  }
+
+  @Test
+  public void testDeleteSubtreeThenQueryOrder() throws Exception {
+    prepareComplexSchema();
+    try (Connection connection = EnvFactory.getEnv().getConnection();
+        Statement statement = connection.createStatement()) {
+      statement.execute("delete timeseries root.db2.devC.**");
+    }
+
+    List<String> expected = new ArrayList<>(BASE_TIMESERIES);
+    expected.remove("root.db2.devC.m0");
+    expected.remove("root.db2.devC.m3");
+    Collections.sort(expected);
+
+    List<String> actual = queryTimeseries("show timeseries root.db*.** order by timeseries");
+    assertEquals(expected, actual);
+  }
+
+  @Test
+  public void testOffsetLimitAfterDeletesAndAdds() throws Exception {
+    prepareComplexSchema();
+    try (Connection connection = EnvFactory.getEnv().getConnection();
+        Statement statement = connection.createStatement()) {
+      statement.execute("delete timeseries root.db1.devB.x");
+      statement.execute(
+          "create timeseries root.db1.devC.m0 with datatype=INT32, encoding=RLE, compression=SNAPPY");
+      statement.execute(
+          "create timeseries root.db4.devZ.z with datatype=INT32, encoding=RLE, compression=SNAPPY");
+    }
+
+    List<String> expected = new ArrayList<>(BASE_TIMESERIES);
+    expected.remove("root.db1.devB.x");
+    expected.add("root.db1.devC.m0");
+    expected.add("root.db4.devZ.z");
+    Collections.sort(expected);
+    expected = expected.subList(5, 10); // offset 5 limit 5
+
+    List<String> actual =
+        queryTimeseries("show timeseries root.db*.** order by timeseries offset 5 limit 5");
+    assertEquals(expected, actual);
+  }

Review Comment:
   The new tests validate basic ordering/offset/limit behavior, but they don't cover the interaction of ORDER BY TIMESERIES with a timeseries WHERE clause + OFFSET (schemaFilter). Given offset is now pushed down in single-region queries, adding a case like "SHOW TIMESERIES ... WHERE timeseries contains ... ORDER BY TIMESERIES OFFSET ..." would help prevent regressions in offset semantics under filtering.



##########
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/schemaengine/schemaregion/mtree/impl/mem/MTreeBelowSGMemoryImpl.java:
##########
@@ -1435,6 +1479,46 @@ public ISchemaReader<ITimeSeriesSchemaInfo> getTimeSeriesReader(
             showTimeSeriesPlan.isPrefixMatch(),
             showTimeSeriesPlan.getScope()) {
 
+          private long remainingOffset = Math.max(0, showTimeSeriesPlan.getOffset());
+
+          private boolean shouldPruneSubtree(final IMemMNode node) {
+            if (remainingOffset <= 0) {
+              return false;
+            }
+            final long subtreeCount = node.getSubtreeMeasurementCount();
+            if (subtreeCount <= remainingOffset) {
+              remainingOffset -= subtreeCount;
+              return true;
+            }
+            return false;
+          }
+
+          @Override
+          protected boolean acceptFullMatchedNode(final IMemMNode node) {
+            if (!node.isMeasurement()) {
+              return false;
+            }
+            if (remainingOffset > 0) {
+              // skip this measurement
+              remainingOffset--;
+              return false;
+            }
+            return true;
+          }

Review Comment:
   In single-schema-region queries, OFFSET is now consumed inside MeasurementCollector (remainingOffset/shouldPruneSubtree/acceptFullMatchedNode) before TimeseriesReaderWithViewFetch applies schemaFilter. This changes semantics when a timeseries WHERE clause is present: OFFSET should apply to the filtered result set, not to the pre-filter traversal order. Consider disabling the offset-pruning pushdown when showTimeSeriesPlan.getSchemaFilter() is non-null (keep SchemaReaderLimitOffsetWrapper offset), or push schemaFilter evaluation into the collector so remainingOffset is decremented/pruned only for matched results.



##########
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/statement/metadata/ShowStatement.java:
##########
@@ -59,6 +59,13 @@ public void setOffset(long offset) {
     this.offset = offset;
   }
 
+  public long getLimitWithOffset() {
+    if (limit <= 0) {
+      return limit;
+    }

Review Comment:
   getLimitWithOffset() returns limit + offset without overflow handling. With large LIMIT/OFFSET literals this can overflow to a negative value and lead to incorrect planning. Consider using Math.addExact with a friendly error, or clamping to Long.MAX_VALUE when the sum would overflow.
   ```suggestion
       }
       // Guard against overflow when adding limit and offset.
       if (offset > 0 && limit > Long.MAX_VALUE - offset) {
         // Clamp to Long.MAX_VALUE to avoid negative or incorrect values due to overflow.
         return Long.MAX_VALUE;
       }
   ```



##########
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/schemaengine/schemaregion/mtree/impl/mem/mnode/basic/BasicMNode.java:
##########
@@ -46,6 +46,9 @@ public class BasicMNode implements IMemMNode {
   private IMemMNode parent;
   private final BasicMNodeInfo basicMNodeInfo;
 
+  /** Cached count of measurements in this node's subtree, restored on restart. */

Review Comment:
   The new subtreeMeasurementCount field is described as "restored on restart", but this value is not persisted and is rebuilt in memory (e.g., via rebuildSubtreeMeasurementCount()). Consider rewording to avoid implying persistence (e.g., "rebuilt on restart" / "recomputed on load").
   ```suggestion
     /** Cached count of measurements in this node's subtree, rebuilt on restart. */
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@iotdb.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat: show timeseries [order by timseries] clause [iotdb]

Posted by "xiangmy21 (via GitHub)" <gi...@apache.org>.
xiangmy21 commented on code in PR #17065:
URL: https://github.com/apache/iotdb/pull/17065#discussion_r2759067597


##########
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/planner/plan/node/process/ActiveRegionScanMergeNode.java:
##########
@@ -70,6 +70,9 @@ public PlanNode clone() {
 
   @Override
   public List<String> getOutputColumnNames() {
+    if (!children.isEmpty()) {
+      return children.get(0).getOutputColumnNames();
+    }

Review Comment:
   The showDevicesColumnHeaders does not contains the 'Timeseries' type we need for sort operation. It contains 'Device' instead of 'Timeseries'. Without this modification the execution will raise error: org.apache.iotdb.jdbc.IoTDBSQLException: 301: Cannot invoke "org.apache.tsfile.enums.TSDataType.ordinal()" because the return value of "java.util.List.get(int)" is null



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@iotdb.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat: show timeseries [order by timseries] clause [iotdb]

Posted by "xiangmy21 (via GitHub)" <gi...@apache.org>.
xiangmy21 commented on code in PR #17065:
URL: https://github.com/apache/iotdb/pull/17065#discussion_r2759067597


##########
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/planner/plan/node/process/ActiveRegionScanMergeNode.java:
##########
@@ -70,6 +70,9 @@ public PlanNode clone() {
 
   @Override
   public List<String> getOutputColumnNames() {
+    if (!children.isEmpty()) {
+      return children.get(0).getOutputColumnNames();
+    }

Review Comment:
   The showDevicesColumnHeaders does not contains the 'Timeseries' type we need for sort operation. It contains 'Device' instead of 'Timeseries'. Without this modification the execution of `show timeseries root.sg4.** where time > 0 order by timeseries` will raise error: org.apache.iotdb.jdbc.IoTDBSQLException: 301: Cannot invoke "org.apache.tsfile.enums.TSDataType.ordinal()" because the return value of "java.util.List.get(int)" is null



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@iotdb.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat: show timeseries [order by timseries] clause [iotdb]

Posted by "JackieTien97 (via GitHub)" <gi...@apache.org>.
JackieTien97 commented on code in PR #17065:
URL: https://github.com/apache/iotdb/pull/17065#discussion_r2757818919


##########
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/thrift/impl/DataNodeInternalRPCServiceImpl.java:
##########
@@ -2571,7 +2573,19 @@ public TSStatus updateTemplate(final TUpdateTemplateReq req) {
         ClusterTemplateManager.getInstance().commitTemplatePreSetInfo(req.getTemplateInfo());
         break;
       case UPDATE_TEMPLATE_INFO:
+        Template newTemplate =
+            TemplateInternalRPCUtil.parseUpdateTemplateInfoBytes(
+                ByteBuffer.wrap(req.getTemplateInfo()));
+        Template oldTemplate =
+            ClusterTemplateManager.getInstance().getTemplate(newTemplate.getId());
         ClusterTemplateManager.getInstance().updateTemplateInfo(req.getTemplateInfo());

Review Comment:
   pass `newTemplate` directly into ClusterTemplateManager.getInstance().updateTemplateInfo instead of parsing it again.



##########
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/operator/schema/source/TimeSeriesSchemaSource.java:
##########
@@ -54,6 +54,8 @@ public class TimeSeriesSchemaSource implements ISchemaSource<ITimeSeriesSchemaIn
   private final SchemaFilter schemaFilter;
   private final Map<Integer, Template> templateMap;
   private final boolean needViewDetail;
+  private final boolean orderByTimeseries;
+  private final boolean orderByTimeseriesDesc;

Review Comment:
   just one `private final Boolean orderByTimeseries` field is enough? and then some comments, like: null for no order by, Boolean.TRUE for asc, Boolean.FALSE for desc.



##########
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/planner/plan/node/metadata/read/TimeSeriesSchemaScanNode.java:
##########
@@ -48,6 +48,11 @@ public class TimeSeriesSchemaScanNode extends SchemaQueryScanNode {
   // if is true, the result will be sorted according to the inserting frequency of the timeseries
   private final boolean orderByHeat;
 
+  // Whether to order result by timeseries full path in this region.
+  private final boolean orderByTimeseries;
+  // When orderByTimeseries is true, whether the ordering is descending.
+  private final boolean orderByTimeseriesDesc;
+

Review Comment:
   same as above.



##########
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/planner/plan/node/process/ActiveRegionScanMergeNode.java:
##########
@@ -70,6 +70,9 @@ public PlanNode clone() {
 
   @Override
   public List<String> getOutputColumnNames() {
+    if (!children.isEmpty()) {
+      return children.get(0).getOutputColumnNames();
+    }

Review Comment:
   why we need to do this change? The origin codes should still take effect.
   ```
   ColumnHeaderConstant.showDevicesColumnHeaders.stream()
               .map(ColumnHeader::getColumnName)
               .collect(Collectors.toList())
   ```



##########
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/schemaengine/schemaregion/read/req/impl/ShowTimeSeriesPlanImpl.java:
##########
@@ -37,6 +37,10 @@ public class ShowTimeSeriesPlanImpl extends AbstractShowSchemaPlanImpl
   private final SchemaFilter schemaFilter;
   private final boolean needViewDetail;
 
+  // order-by-timeseries pushdown flags inside a single SchemaRegion
+  private final boolean orderByTimeseries;
+  private final boolean orderByTimeseriesDesc;
+

Review Comment:
   same as above



##########
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/statement/metadata/ShowTimeSeriesStatement.java:
##########
@@ -42,6 +43,9 @@ public class ShowTimeSeriesStatement extends ShowStatement {
   // if is true, the result will be sorted according to the inserting frequency of the time series
   private final boolean orderByHeat;
   private WhereCondition timeCondition;
+  // order by timeseries name
+  private boolean orderByTimeseries;
+  private Ordering nameOrdering = Ordering.ASC;

Review Comment:
   why it's called nameOrdering? just order is enough?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@iotdb.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat: show timeseries [order by timseries] clause [iotdb]

Posted by "xiangmy21 (via GitHub)" <gi...@apache.org>.
xiangmy21 commented on code in PR #17065:
URL: https://github.com/apache/iotdb/pull/17065#discussion_r2734536845


##########
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/schemaengine/schemaregion/mtree/impl/mem/MTreeBelowSGMemoryImpl.java:
##########
@@ -192,6 +193,22 @@ public synchronized boolean createSnapshot(final File snapshotDir) {
     return store.createSnapshot(snapshotDir);
   }
 
+  private void applySubtreeMeasurementDelta(IMemMNode startNode, final long delta) {
+    if (delta == 0 || startNode == null) {
+      return;
+    }
+    IMemMNode current = startNode;
+    while (current != null) {
+      current.setSubtreeMeasurementCount(current.getSubtreeMeasurementCount() + delta);
+      current = current.getParent();
+    }
+  }
+
+  private long getTemplateMeasurementCount(final int templateId) {
+    final Template template = ClusterTemplateManager.getInstance().getTemplate(templateId);
+    return template == null ? 0L : template.getMeasurementNumber();

Review Comment:
   Great catch! I fixed this issue in commit [4027f97](https://github.com/apache/iotdb/pull/17065/commits/4027f9724ad417771b64eff82a53c90180a47297). When a template is modified, the update is broadcast to the corresponding SchemaRegion, and the subtree statistics are updated upward from the nodes activated by the template in the MTree.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@iotdb.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat: show timeseries [order by timseries] clause [iotdb]

Posted by "xiangmy21 (via GitHub)" <gi...@apache.org>.
xiangmy21 commented on code in PR #17065:
URL: https://github.com/apache/iotdb/pull/17065#discussion_r2734541354


##########
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/schemaengine/schemaregion/mtree/impl/mem/MTreeBelowSGMemoryImpl.java:
##########
@@ -1123,6 +1150,23 @@ public long countPathsUsingTemplate(final PartialPath pathPattern, final int tem
     }
   }
 
+  public void rebuildSubtreeMeasurementCount() {
+    rebuildSubtreeMeasurementCountFromNode(rootNode);
+  }
+
+  private long rebuildSubtreeMeasurementCountFromNode(final IMemMNode node) {
+    long count = node.isMeasurement() ? 1L : 0L;
+    final IMNodeIterator<IMemMNode> iterator = store.getChildrenIterator(node);
+    while (iterator.hasNext()) {
+      count += rebuildSubtreeMeasurementCountFromNode(iterator.next());

Review Comment:
   The intermediate logic here is unlikely to throw exceptions, and the iterator will be automatically closed when the function returns. Therefore, we do not modify it for now.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@iotdb.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat: show timeseries [order by timseries] clause [iotdb]

Posted by "xiangmy21 (via GitHub)" <gi...@apache.org>.
xiangmy21 commented on code in PR #17065:
URL: https://github.com/apache/iotdb/pull/17065#discussion_r2734553589


##########
integration-test/src/test/java/org/apache/iotdb/db/it/schema/IoTDBShowTimeseriesOrderByTimeseriesIT.java:
##########
@@ -0,0 +1,221 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iotdb.db.it.schema;
+
+import org.apache.iotdb.commons.schema.column.ColumnHeaderConstant;
+import org.apache.iotdb.it.env.EnvFactory;
+import org.apache.iotdb.itbase.category.ClusterIT;
+import org.apache.iotdb.itbase.category.LocalStandaloneIT;
+import org.apache.iotdb.util.AbstractSchemaIT;
+
+import org.junit.After;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+import org.junit.runners.Parameterized;
+
+import java.sql.Connection;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+@Category({LocalStandaloneIT.class, ClusterIT.class})
+public class IoTDBShowTimeseriesOrderByTimeseriesIT extends AbstractSchemaIT {
+
+  private static final List<String> BASE_TIMESERIES =
+      Arrays.asList(
+          "root.db1.devA.m1",
+          "root.db1.devA.m2",
+          "root.db1.devB.m1",
+          "root.db1.devB.x",
+          "root.db2.devA.m1",
+          "root.db2.devC.m0",
+          "root.db2.devC.m3",
+          "root.db3.z.m1",
+          "root.db3.z.m10",
+          "root.db3.z.m2");
+
+  public IoTDBShowTimeseriesOrderByTimeseriesIT(SchemaTestMode schemaTestMode) {
+    super(schemaTestMode);
+  }
+
+  @Parameterized.BeforeParam
+  public static void before() throws Exception {
+    setUpEnvironment();
+    EnvFactory.getEnv().initClusterEnvironment();
+  }
+
+  @Parameterized.AfterParam
+  public static void after() throws Exception {
+    EnvFactory.getEnv().cleanClusterEnvironment();
+    tearDownEnvironment();
+  }
+
+  @After
+  public void tearDown() throws Exception {
+    clearSchema();
+  }
+
+  private void prepareComplexSchema() throws Exception {
+    try (Connection connection = EnvFactory.getEnv().getConnection();
+        Statement statement = connection.createStatement()) {
+      statement.execute("CREATE DATABASE root.db1");
+      statement.execute("CREATE DATABASE root.db2");
+      statement.execute("CREATE DATABASE root.db3");
+
+      for (String ts : BASE_TIMESERIES) {
+        statement.execute(
+            String.format(
+                "create timeseries %s with datatype=INT32, encoding=RLE, compression=SNAPPY", ts));
+      }
+    }
+  }
+
+  private List<String> queryTimeseries(final String sql) throws Exception {
+    try (Connection connection = EnvFactory.getEnv().getConnection();
+        Statement statement = connection.createStatement();
+        ResultSet resultSet = statement.executeQuery(sql)) {
+      List<String> result = new ArrayList<>();
+      while (resultSet.next()) {
+        result.add(resultSet.getString(ColumnHeaderConstant.TIMESERIES));
+      }
+      return result;
+    }
+  }
+
+  @Test
+  public void testOrderAscWithoutLimit() throws Exception {
+    prepareComplexSchema();
+    List<String> expected = new ArrayList<>(BASE_TIMESERIES);
+    Collections.sort(expected);
+
+    List<String> actual = queryTimeseries("show timeseries root.db*.** order by timeseries");
+    assertEquals(expected, actual);
+  }
+
+  @Test
+  public void testOrderDescWithOffsetLimit() throws Exception {
+    prepareComplexSchema();
+    List<String> expected = new ArrayList<>(BASE_TIMESERIES);
+    Collections.sort(expected);
+    Collections.reverse(expected);
+    expected = expected.subList(2, 6); // offset 2 limit 4
+
+    List<String> actual =
+        queryTimeseries("show timeseries root.db*.** order by timeseries desc offset 2 limit 4");
+    assertEquals(expected, actual);
+  }
+
+  @Test
+  public void testInsertThenQueryOrder() throws Exception {
+    prepareComplexSchema();
+    try (Connection connection = EnvFactory.getEnv().getConnection();
+        Statement statement = connection.createStatement()) {
+      statement.execute(
+          "create timeseries root.db0.devX.a with datatype=INT32, encoding=RLE, compression=SNAPPY");
+    }
+
+    List<String> expected = new ArrayList<>(BASE_TIMESERIES);
+    expected.add("root.db0.devX.a");
+    Collections.sort(expected);
+
+    List<String> actual = queryTimeseries("show timeseries root.db*.** order by timeseries");
+    assertEquals(expected, actual);
+  }
+
+  @Test
+  public void testDeleteSubtreeThenQueryOrder() throws Exception {
+    prepareComplexSchema();
+    try (Connection connection = EnvFactory.getEnv().getConnection();
+        Statement statement = connection.createStatement()) {
+      statement.execute("delete timeseries root.db2.devC.**");
+    }
+
+    List<String> expected = new ArrayList<>(BASE_TIMESERIES);
+    expected.remove("root.db2.devC.m0");
+    expected.remove("root.db2.devC.m3");
+    Collections.sort(expected);
+
+    List<String> actual = queryTimeseries("show timeseries root.db*.** order by timeseries");
+    assertEquals(expected, actual);
+  }
+
+  @Test
+  public void testOffsetLimitAfterDeletesAndAdds() throws Exception {
+    prepareComplexSchema();
+    try (Connection connection = EnvFactory.getEnv().getConnection();
+        Statement statement = connection.createStatement()) {
+      statement.execute("delete timeseries root.db1.devB.x");
+      statement.execute(
+          "create timeseries root.db1.devC.m0 with datatype=INT32, encoding=RLE, compression=SNAPPY");
+      statement.execute(
+          "create timeseries root.db4.devZ.z with datatype=INT32, encoding=RLE, compression=SNAPPY");
+    }
+
+    List<String> expected = new ArrayList<>(BASE_TIMESERIES);
+    expected.remove("root.db1.devB.x");
+    expected.add("root.db1.devC.m0");
+    expected.add("root.db4.devZ.z");
+    Collections.sort(expected);
+    expected = expected.subList(5, 10); // offset 5 limit 5
+
+    List<String> actual =
+        queryTimeseries("show timeseries root.db*.** order by timeseries offset 5 limit 5");
+    assertEquals(expected, actual);
+  }

Review Comment:
   Good point! I’ve added test cases to cover the interaction between the WHERE clause and OFFSET, as well as runtime template modification scenarios, in commit [c56e155](https://github.com/apache/iotdb/pull/17065/commits/c56e155754074d42eed1396b4304929b1bb0bce5).



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@iotdb.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat: show timeseries [order by timseries] clause [iotdb]

Posted by "JackieTien97 (via GitHub)" <gi...@apache.org>.
JackieTien97 merged PR #17065:
URL: https://github.com/apache/iotdb/pull/17065


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@iotdb.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat: show timeseries [order by timseries] clause [iotdb]

Posted by "xiangmy21 (via GitHub)" <gi...@apache.org>.
xiangmy21 commented on code in PR #17065:
URL: https://github.com/apache/iotdb/pull/17065#discussion_r2759004016


##########
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/operator/schema/source/TimeSeriesSchemaSource.java:
##########
@@ -54,6 +54,8 @@ public class TimeSeriesSchemaSource implements ISchemaSource<ITimeSeriesSchemaIn
   private final SchemaFilter schemaFilter;
   private final Map<Integer, Template> templateMap;
   private final boolean needViewDetail;
+  private final boolean orderByTimeseries;
+  private final boolean orderByTimeseriesDesc;

Review Comment:
   To clarify its function, I'll use an Ordering enum to replace these two boolean. See commit [2121c9a](https://github.com/apache/iotdb/pull/17065/commits/2121c9aec2c5f994f1ed6d2f63c8f9fc5abdfb25)



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@iotdb.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat: show timeseries [order by timseries] clause [iotdb]

Posted by "xiangmy21 (via GitHub)" <gi...@apache.org>.
xiangmy21 commented on code in PR #17065:
URL: https://github.com/apache/iotdb/pull/17065#discussion_r2734546826


##########
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/statement/metadata/ShowStatement.java:
##########
@@ -59,6 +59,13 @@ public void setOffset(long offset) {
     this.offset = offset;
   }
 
+  public long getLimitWithOffset() {
+    if (limit <= 0) {
+      return limit;
+    }

Review Comment:
   Both limit and offset are of type long, so overflow is unlikely in practice.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@iotdb.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat: show timeseries [order by timseries] clause [iotdb]

Posted by "xiangmy21 (via GitHub)" <gi...@apache.org>.
xiangmy21 commented on code in PR #17065:
URL: https://github.com/apache/iotdb/pull/17065#discussion_r2734528415


##########
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/schemaengine/schemaregion/mtree/impl/mem/MTreeBelowSGMemoryImpl.java:
##########
@@ -1435,6 +1479,46 @@ public ISchemaReader<ITimeSeriesSchemaInfo> getTimeSeriesReader(
             showTimeSeriesPlan.isPrefixMatch(),
             showTimeSeriesPlan.getScope()) {
 
+          private long remainingOffset = Math.max(0, showTimeSeriesPlan.getOffset());
+
+          private boolean shouldPruneSubtree(final IMemMNode node) {
+            if (remainingOffset <= 0) {
+              return false;
+            }
+            final long subtreeCount = node.getSubtreeMeasurementCount();
+            if (subtreeCount <= remainingOffset) {
+              remainingOffset -= subtreeCount;
+              return true;
+            }
+            return false;
+          }
+
+          @Override
+          protected boolean acceptFullMatchedNode(final IMemMNode node) {
+            if (!node.isMeasurement()) {
+              return false;
+            }
+            if (remainingOffset > 0) {
+              // skip this measurement
+              remainingOffset--;
+              return false;
+            }
+            return true;
+          }

Review Comment:
   Exactly! I fixed this issue in #[0177c66](https://github.com/apache/iotdb/pull/17065/commits/0177c6699654a66f38fb92809c28c65551a3419a)
    by disabling pushdown when schemaFilter is present, and by refining the subtree-skipping logic: a subtree is skipped only when its nodes are fully covered by the path pattern.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@iotdb.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat: show timeseries [order by timseries] clause [iotdb]

Posted by "xiangmy21 (via GitHub)" <gi...@apache.org>.
xiangmy21 commented on code in PR #17065:
URL: https://github.com/apache/iotdb/pull/17065#discussion_r2758984052


##########
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/thrift/impl/DataNodeInternalRPCServiceImpl.java:
##########
@@ -2571,7 +2573,19 @@ public TSStatus updateTemplate(final TUpdateTemplateReq req) {
         ClusterTemplateManager.getInstance().commitTemplatePreSetInfo(req.getTemplateInfo());
         break;
       case UPDATE_TEMPLATE_INFO:
+        Template newTemplate =
+            TemplateInternalRPCUtil.parseUpdateTemplateInfoBytes(
+                ByteBuffer.wrap(req.getTemplateInfo()));
+        Template oldTemplate =
+            ClusterTemplateManager.getInstance().getTemplate(newTemplate.getId());
         ClusterTemplateManager.getInstance().updateTemplateInfo(req.getTemplateInfo());

Review Comment:
   solved in commit [42e1528](https://github.com/apache/iotdb/pull/17065/commits/42e1528e35fd1dab3d2db97abc2dd5de3c710720)



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@iotdb.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org