You are viewing a plain text version of this content. The canonical link for it is here.
Posted to reviews@iotdb.apache.org by "Wei-hao-Li (via GitHub)" <gi...@apache.org> on 2023/07/19 05:44:21 UTC

[GitHub] [iotdb] Wei-hao-Li opened a new pull request, #10600: Add last RPC

Wei-hao-Li opened a new pull request, #10600:
URL: https://github.com/apache/iotdb/pull/10600

   ## Description
   
   
   ### Content1 ...
   
   ### Content2 ...
   
   ### Content3 ...
   
   <!--
   In each section, please describe design decisions made, including:
    - Choice of algorithms
    - Behavioral aspects. What configuration values are acceptable? How are corner cases and error 
       conditions handled, such as when there are insufficient resources?
    - Class organization and design (how the logic is split between classes, inheritance, composition, 
       design patterns)
    - Method organization and design (how the logic is split between methods, parameters and return types)
    - Naming (class, method, API, configuration, HTTP endpoint, names of emitted metrics)
   -->
   
   
   <!-- It's good to describe an alternative design (or mention an alternative name) for every design 
   (or naming) decision point and compare the alternatives with the designs that you've implemented 
   (or the names you've chosen) to highlight the advantages of the chosen designs and names. -->
   
   <!-- If there was a discussion of the design of the feature implemented in this PR elsewhere 
   (e. g. a "Proposal" issue, any other issue, or a thread in the development mailing list), 
   link to that discussion from this PR description and explain what have changed in your final design 
   compared to your original proposal or the consensus version in the end of the discussion. 
   If something hasn't changed since the original discussion, you can omit a detailed discussion of 
   those aspects of the design here, perhaps apart from brief mentioning for the sake of readability 
   of this PR description. -->
   
   <!-- Some of the aspects mentioned above may be omitted for simple and small changes. -->
   
   <hr>
   
   This PR has:
   - [ ] been self-reviewed.
       - [ ] concurrent read
       - [ ] concurrent write
       - [ ] concurrent read and write 
   - [ ] added documentation for new or modified features or behaviors.
   - [ ] added Javadocs for most classes and all non-trivial methods. 
   - [ ] added or updated version, __license__, or notice information
   - [ ] added comments explaining the "why" and the intent of the code wherever would not be obvious 
     for an unfamiliar reader.
   - [ ] added unit tests or modified existing tests to cover new code paths, ensuring the threshold 
     for code coverage.
   - [ ] added integration tests.
   - [ ] been tested in a test IoTDB cluster.
   
   <!-- Check the items by putting "x" in the brackets for the done things. Not all of these items 
   apply to every PR. Remove the items which are not done or not relevant to the PR. None of the items 
   from the checklist above are strictly necessary, but it would be very helpful if you at least 
   self-review the PR. -->
   
   <hr>
   
   ##### Key changed/added classes (or packages if there are too many classes) in this PR
   


-- 
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


[GitHub] [iotdb] JackieTien97 merged pull request #10600: Add session interface of faster last query in one device

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


-- 
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


[GitHub] [iotdb] JackieTien97 commented on a diff in pull request #10600: Add session interface of faster last query in one device

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


##########
example/session/src/main/java/org/apache/iotdb/SessionPoolExample.java:
##########
@@ -68,17 +67,54 @@ private static void constructRedirectSessionPool() {
   }
 
   public static void main(String[] args)
-      throws StatementExecutionException, IoTDBConnectionException, InterruptedException {
+      throws StatementExecutionException, IoTDBConnectionException {
     // Choose the SessionPool you going to use
     constructRedirectSessionPool();
 
-    service = Executors.newFixedThreadPool(10);
-    insertRecord();
-    queryByRowRecord();
-    Thread.sleep(1000);
-    queryByIterator();
+    //    service = Executors.newFixedThreadPool(10);
+    //    insertRecord();
+    //    queryByRowRecord();
+    //    Thread.sleep(1000);
+    //    queryByIterator();
+
+    SessionDataSetWrapper sessionDataSetWrapper =
+        sessionPool.executeLastDataQueryForOneDevice(
+            "root.ca.condition",
+            "root.ca.condition.`123456789`",
+            Arrays.asList("Pa", "Pb", "Pc", "status", "Pd"));
+
+    while (sessionDataSetWrapper.hasNext()) {
+      System.out.println(sessionDataSetWrapper.next());
+    }
+
+    sessionDataSetWrapper.close();
+
+    sessionDataSetWrapper =
+        sessionPool.executeLastDataQueryForOneDevice(
+            "root.ca.condition",
+            "root.ca.condition.`123456789`",
+            Arrays.asList("Pa", "Pb", "Pc", "status", "Pd"));
+
+    while (sessionDataSetWrapper.hasNext()) {
+      System.out.println(sessionDataSetWrapper.next());
+    }
+
+    sessionDataSetWrapper.close();
+
+    sessionDataSetWrapper =
+        sessionPool.executeLastDataQueryForOneDevice(
+            "root.ca.condition",
+            "root.ca.condition.`123456789`",
+            Arrays.asList("Pa", "Pb", "Pc", "status", "Pd"));
+
+    while (sessionDataSetWrapper.hasNext()) {
+      System.out.println(sessionDataSetWrapper.next());
+    }
+
+    sessionDataSetWrapper.close();
+
     sessionPool.close();
-    service.shutdown();
+    //    service.shutdown();

Review Comment:
   change it back, you can add a example for the new interface.



##########
iotdb-client/session/src/main/java/org/apache/iotdb/session/SessionConnection.java:
##########
@@ -452,12 +454,60 @@ protected SessionDataSet executeRawDataQuery(
         execResp.moreData);
   }
 
+  protected Pair<SessionDataSet, TEndPoint> executeLastDataQueryForOneDevice(
+      String db, String device, List<String> sensors, long timeOut)
+      throws StatementExecutionException, IoTDBConnectionException {
+    TSFastLastDataQueryForOneDeviceReq req =
+        new TSFastLastDataQueryForOneDeviceReq(sessionId, db, device, sensors, statementId);
+    req.setFetchSize(session.fetchSize);
+    req.setEnableRedirectQuery(enableRedirect);
+    req.setLegalPathNodes(true);

Review Comment:
   make it as a parameter and default is false.



##########
iotdb-client/session/src/main/java/org/apache/iotdb/session/SessionConnection.java:
##########
@@ -452,12 +454,60 @@ protected SessionDataSet executeRawDataQuery(
         execResp.moreData);
   }
 
+  protected Pair<SessionDataSet, TEndPoint> executeLastDataQueryForOneDevice(
+      String db, String device, List<String> sensors, long timeOut)
+      throws StatementExecutionException, IoTDBConnectionException {
+    TSFastLastDataQueryForOneDeviceReq req =
+        new TSFastLastDataQueryForOneDeviceReq(sessionId, db, device, sensors, statementId);
+    req.setFetchSize(session.fetchSize);
+    req.setEnableRedirectQuery(enableRedirect);
+    req.setLegalPathNodes(true);
+    req.setTimeout(timeOut);
+    TSExecuteStatementResp tsExecuteStatementResp = null;
+    TEndPoint redirectedEndPoint = null;
+    try {
+      tsExecuteStatementResp = client.executeFastLastDataQueryForOneDeviceV2(req);
+      RpcUtils.verifySuccessWithRedirection(tsExecuteStatementResp.getStatus());
+    } catch (RedirectException e) {
+      redirectedEndPoint = e.getEndPoint();
+    } catch (TException e) {
+      if (reconnect()) {
+        try {
+          req.setSessionId(sessionId);
+          req.setStatementId(statementId);
+          tsExecuteStatementResp = client.executeFastLastDataQueryForOneDeviceV2(req);
+        } catch (TException tException) {
+          throw new IoTDBConnectionException(tException);
+        }
+      } else {
+        throw new IoTDBConnectionException(logForReconnectionFailure());
+      }
+    }
+
+    RpcUtils.verifySuccess(tsExecuteStatementResp.getStatus());
+    return new Pair<>(
+        new SessionDataSet(
+            "",
+            tsExecuteStatementResp.getColumns(),
+            tsExecuteStatementResp.getDataTypeList(),
+            tsExecuteStatementResp.columnNameIndexMap,
+            tsExecuteStatementResp.getQueryId(),
+            statementId,
+            client,
+            sessionId,
+            tsExecuteStatementResp.queryResult,
+            tsExecuteStatementResp.isIgnoreTimeStamp(),
+            tsExecuteStatementResp.moreData),
+        redirectedEndPoint);
+  }
+
   protected SessionDataSet executeLastDataQuery(List<String> paths, long time, long timeOut)
       throws StatementExecutionException, IoTDBConnectionException, RedirectException {
     TSLastDataQueryReq tsLastDataQueryReq =
         new TSLastDataQueryReq(sessionId, paths, time, statementId);
     tsLastDataQueryReq.setFetchSize(session.fetchSize);
     tsLastDataQueryReq.setEnableRedirectQuery(enableRedirect);
+    tsLastDataQueryReq.setLegalPathNodes(true);

Review Comment:
   ```suggestion
   ```
   default should be false



##########
iotdb-core/datanode/src/test/resources/datanode1conf/iotdb-datanode.properties:
##########
@@ -17,7 +17,7 @@
 # under the License.
 #
 
-dn_rpc_address=0.0.0.0
+dn_rpc_address=127.0.0.1

Review Comment:
   ```suggestion
   dn_rpc_address=0.0.0.0
   ```



##########
iotdb-core/datanode/src/test/resources/datanode2conf/iotdb-datanode.properties:
##########
@@ -17,7 +17,7 @@
 # under the License.
 #
 
-dn_rpc_address=0.0.0.0
+dn_rpc_address=127.0.0.1

Review Comment:
   ```suggestion
   dn_rpc_address=0.0.0.0
   ```



##########
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/buffer/TimeSeriesMetadataCache.java:
##########
@@ -161,7 +161,7 @@ public TimeseriesMetadata get(
           if (timeseriesMetadata == null) {
             cacheHit = false;
 
-            Path path = new Path(key.device, key.measurement, true);
+            Path path = new Path(key.device, key.measurement, false);

Review Comment:
   ```suggestion
               Path path = new Path(key.device, key.measurement, true);
   ```
   change it back.



##########
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/thrift/impl/ClientRPCServiceImpl.java:
##########
@@ -583,6 +601,207 @@ public TSExecuteStatementResp executeLastDataQueryV2(TSLastDataQueryReq req) {
     return executeLastDataQueryInternal(req, SELECT_RESULT);
   }
 
+  @Override
+  public TSExecuteStatementResp executeFastLastDataQueryForOneDeviceV2(
+      TSFastLastDataQueryForOneDeviceReq req) {
+    boolean finished = false;
+    long queryId = Long.MIN_VALUE;
+    IClientSession clientSession = SESSION_MANAGER.getCurrSessionAndUpdateIdleTime();
+    OperationQuota quota = null;
+    if (!SESSION_MANAGER.checkLogin(clientSession)) {
+      return RpcUtils.getTSExecuteStatementResp(getNotLoggedInStatus());
+    }
+    long startTime = System.currentTimeMillis();
+    long startNanoTime = System.nanoTime();
+    Throwable t = null;
+    try {
+      String db;
+      String deviceId;
+      PartialPath devicePath;
+
+      queryId = SESSION_MANAGER.requestQueryId(clientSession, req.statementId);
+
+      if (req.isLegalPathNodes()) {
+        db = req.db;
+        deviceId = req.deviceId;
+        devicePath = new PartialPath(deviceId.split("\\."));
+      } else {
+        db = new PartialPath(req.db).getFullPath();
+        devicePath = new PartialPath(req.deviceId);
+        deviceId = devicePath.getFullPath();
+      }
+
+      DataPartitionQueryParam queryParam =
+          new DataPartitionQueryParam(deviceId, Collections.emptyList(), true, true);
+      DataPartition dataPartition =
+          partitionFetcher.getDataPartitionWithUnclosedTimeRange(
+              Collections.singletonMap(db, Collections.singletonList(queryParam)));
+      List<TRegionReplicaSet> regionReplicaSets =
+          dataPartition.getDataRegionReplicaSet(deviceId, Collections.emptyList());
+
+      // no schema
+      if (regionReplicaSets.isEmpty()
+          || regionReplicaSets.size() == 1 && NOT_ASSIGNED == regionReplicaSets.get(0)) {
+        TSExecuteStatementResp resp =
+            createResponse(DatasetHeaderFactory.getLastQueryHeader(), queryId);
+        resp.setStatus(RpcUtils.getStatus(TSStatusCode.SUCCESS_STATUS, ""));
+        resp.setQueryResult(Collections.emptyList());
+        finished = true;
+        resp.setMoreData(true);

Review Comment:
   ```suggestion
           resp.setMoreData(false);
   ```



##########
iotdb-core/datanode/src/test/resources/datanode3conf/iotdb-datanode.properties:
##########
@@ -17,7 +17,7 @@
 # under the License.
 #
 
-dn_rpc_address=0.0.0.0
+dn_rpc_address=127.0.0.1

Review Comment:
   ```suggestion
   dn_rpc_address=0.0.0.0
   ```



##########
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/thrift/impl/ClientRPCServiceImpl.java:
##########
@@ -583,6 +601,207 @@ public TSExecuteStatementResp executeLastDataQueryV2(TSLastDataQueryReq req) {
     return executeLastDataQueryInternal(req, SELECT_RESULT);
   }
 
+  @Override
+  public TSExecuteStatementResp executeFastLastDataQueryForOneDeviceV2(
+      TSFastLastDataQueryForOneDeviceReq req) {
+    boolean finished = false;
+    long queryId = Long.MIN_VALUE;
+    IClientSession clientSession = SESSION_MANAGER.getCurrSessionAndUpdateIdleTime();
+    OperationQuota quota = null;
+    if (!SESSION_MANAGER.checkLogin(clientSession)) {
+      return RpcUtils.getTSExecuteStatementResp(getNotLoggedInStatus());
+    }
+    long startTime = System.currentTimeMillis();
+    long startNanoTime = System.nanoTime();
+    Throwable t = null;
+    try {
+      String db;
+      String deviceId;
+      PartialPath devicePath;
+
+      queryId = SESSION_MANAGER.requestQueryId(clientSession, req.statementId);
+
+      if (req.isLegalPathNodes()) {
+        db = req.db;
+        deviceId = req.deviceId;
+        devicePath = new PartialPath(deviceId.split("\\."));
+      } else {
+        db = new PartialPath(req.db).getFullPath();
+        devicePath = new PartialPath(req.deviceId);
+        deviceId = devicePath.getFullPath();
+      }
+
+      DataPartitionQueryParam queryParam =
+          new DataPartitionQueryParam(deviceId, Collections.emptyList(), true, true);
+      DataPartition dataPartition =
+          partitionFetcher.getDataPartitionWithUnclosedTimeRange(
+              Collections.singletonMap(db, Collections.singletonList(queryParam)));
+      List<TRegionReplicaSet> regionReplicaSets =
+          dataPartition.getDataRegionReplicaSet(deviceId, Collections.emptyList());
+
+      // no schema
+      if (regionReplicaSets.isEmpty()
+          || regionReplicaSets.size() == 1 && NOT_ASSIGNED == regionReplicaSets.get(0)) {
+        TSExecuteStatementResp resp =
+            createResponse(DatasetHeaderFactory.getLastQueryHeader(), queryId);
+        resp.setStatus(RpcUtils.getStatus(TSStatusCode.SUCCESS_STATUS, ""));
+        resp.setQueryResult(Collections.emptyList());
+        finished = true;
+        resp.setMoreData(true);
+        return resp;
+      }
+
+      TEndPoint lastRegionLeader =
+          regionReplicaSets
+              .get(regionReplicaSets.size() - 1)
+              .dataNodeLocations
+              .get(0)
+              .mPPDataExchangeEndPoint;
+      // the device's all dataRegion's leader are on the same node, may can read directly from cache
+      if (isSameNode(lastRegionLeader)) {
+        boolean canUseNullEntry =
+            regionReplicaSets.stream()
+                .limit(regionReplicaSets.size() - 1L)
+                .allMatch(
+                    regionReplicaSet ->
+                        regionReplicaSet
+                            .dataNodeLocations
+                            .get(0)
+                            .mPPDataExchangeEndPoint
+                            .equals(lastRegionLeader));
+        int sensorNum = req.sensors.size();
+        TsBlockBuilder builder = LastQueryUtil.createTsBlockBuilder(sensorNum);
+        boolean allCached = true;
+        for (String sensor : req.sensors) {
+          PartialPath fullPath;
+          if (req.isLegalPathNodes()) {
+            fullPath = devicePath.concatNode(sensor);
+          } else {
+            fullPath = devicePath.concatNode((new PartialPath(sensor)).getFullPath());
+          }
+          TimeValuePair timeValuePair = DATA_NODE_SCHEMA_CACHE.getLastCache(fullPath);
+          if (timeValuePair == null) {
+            allCached = false;
+            break;
+          } else if (timeValuePair.getValue() == null) {
+            // there is no data for this sensor
+            if (!canUseNullEntry) {
+              allCached = false;
+              break;
+            }
+          } else {
+            // we don't consider TTL
+            LastQueryUtil.appendLastValue(
+                builder,
+                timeValuePair.getTimestamp(),
+                new Binary(fullPath.getFullPath()),
+                timeValuePair.getValue().getStringValue(),
+                timeValuePair.getValue().getDataType().name());
+          }
+        }
+        // cache hit
+        if (allCached) {
+          TSExecuteStatementResp resp =
+              createResponse(DatasetHeaderFactory.getLastQueryHeader(), queryId);
+          resp.setStatus(RpcUtils.getStatus(TSStatusCode.SUCCESS_STATUS, ""));
+          if (builder.isEmpty()) {
+            resp.setQueryResult(Collections.emptyList());
+          } else {
+            resp.setQueryResult(Collections.singletonList(serde.serialize(builder.build())));
+          }
+          finished = true;
+          resp.setMoreData(true);

Review Comment:
   ```suggestion
             resp.setMoreData(false);
   ```



##########
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/thrift/impl/ClientRPCServiceImpl.java:
##########
@@ -583,6 +601,207 @@ public TSExecuteStatementResp executeLastDataQueryV2(TSLastDataQueryReq req) {
     return executeLastDataQueryInternal(req, SELECT_RESULT);
   }
 
+  @Override
+  public TSExecuteStatementResp executeFastLastDataQueryForOneDeviceV2(
+      TSFastLastDataQueryForOneDeviceReq req) {
+    boolean finished = false;
+    long queryId = Long.MIN_VALUE;
+    IClientSession clientSession = SESSION_MANAGER.getCurrSessionAndUpdateIdleTime();
+    OperationQuota quota = null;
+    if (!SESSION_MANAGER.checkLogin(clientSession)) {
+      return RpcUtils.getTSExecuteStatementResp(getNotLoggedInStatus());
+    }
+    long startTime = System.currentTimeMillis();

Review Comment:
   never need this.



##########
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/thrift/impl/ClientRPCServiceImpl.java:
##########
@@ -583,6 +601,207 @@ public TSExecuteStatementResp executeLastDataQueryV2(TSLastDataQueryReq req) {
     return executeLastDataQueryInternal(req, SELECT_RESULT);
   }
 
+  @Override
+  public TSExecuteStatementResp executeFastLastDataQueryForOneDeviceV2(
+      TSFastLastDataQueryForOneDeviceReq req) {
+    boolean finished = false;
+    long queryId = Long.MIN_VALUE;
+    IClientSession clientSession = SESSION_MANAGER.getCurrSessionAndUpdateIdleTime();
+    OperationQuota quota = null;
+    if (!SESSION_MANAGER.checkLogin(clientSession)) {
+      return RpcUtils.getTSExecuteStatementResp(getNotLoggedInStatus());
+    }
+    long startTime = System.currentTimeMillis();
+    long startNanoTime = System.nanoTime();
+    Throwable t = null;
+    try {
+      String db;
+      String deviceId;
+      PartialPath devicePath;
+
+      queryId = SESSION_MANAGER.requestQueryId(clientSession, req.statementId);
+
+      if (req.isLegalPathNodes()) {
+        db = req.db;
+        deviceId = req.deviceId;
+        devicePath = new PartialPath(deviceId.split("\\."));
+      } else {
+        db = new PartialPath(req.db).getFullPath();
+        devicePath = new PartialPath(req.deviceId);
+        deviceId = devicePath.getFullPath();
+      }
+
+      DataPartitionQueryParam queryParam =
+          new DataPartitionQueryParam(deviceId, Collections.emptyList(), true, true);
+      DataPartition dataPartition =
+          partitionFetcher.getDataPartitionWithUnclosedTimeRange(
+              Collections.singletonMap(db, Collections.singletonList(queryParam)));
+      List<TRegionReplicaSet> regionReplicaSets =
+          dataPartition.getDataRegionReplicaSet(deviceId, Collections.emptyList());
+
+      // no schema

Review Comment:
   ```suggestion
         // no valid DataRegion
   ```



##########
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/thrift/impl/ClientRPCServiceImpl.java:
##########
@@ -2169,7 +2388,9 @@ public TSStatus insertStringRecord(TSInsertStringRecordReq req) {
           e, OperationType.INSERT_STRING_RECORD, TSStatusCode.EXECUTE_STATEMENT_ERROR);
     } finally {
       addStatementExecutionLatency(
-          OperationType.INSERT_STRING_RECORD, StatementType.INSERT, System.nanoTime() - t1);
+          OperationType.INSERT_STRING_RECORD,
+          StatementType.INSERT,
+          System.currentTimeMillis() - t1);

Review Comment:
   ```suggestion
             OperationType.INSERT_STRING_RECORD, StatementType.INSERT, System.nanoTime() - t1);
   ```
   change it back.



##########
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/thrift/impl/ClientRPCServiceImpl.java:
##########
@@ -583,6 +601,207 @@ public TSExecuteStatementResp executeLastDataQueryV2(TSLastDataQueryReq req) {
     return executeLastDataQueryInternal(req, SELECT_RESULT);
   }
 
+  @Override
+  public TSExecuteStatementResp executeFastLastDataQueryForOneDeviceV2(
+      TSFastLastDataQueryForOneDeviceReq req) {
+    boolean finished = false;
+    long queryId = Long.MIN_VALUE;
+    IClientSession clientSession = SESSION_MANAGER.getCurrSessionAndUpdateIdleTime();
+    OperationQuota quota = null;
+    if (!SESSION_MANAGER.checkLogin(clientSession)) {
+      return RpcUtils.getTSExecuteStatementResp(getNotLoggedInStatus());
+    }
+    long startTime = System.currentTimeMillis();
+    long startNanoTime = System.nanoTime();
+    Throwable t = null;
+    try {
+      String db;
+      String deviceId;
+      PartialPath devicePath;
+
+      queryId = SESSION_MANAGER.requestQueryId(clientSession, req.statementId);
+
+      if (req.isLegalPathNodes()) {
+        db = req.db;
+        deviceId = req.deviceId;
+        devicePath = new PartialPath(deviceId.split("\\."));
+      } else {
+        db = new PartialPath(req.db).getFullPath();
+        devicePath = new PartialPath(req.deviceId);
+        deviceId = devicePath.getFullPath();
+      }
+
+      DataPartitionQueryParam queryParam =
+          new DataPartitionQueryParam(deviceId, Collections.emptyList(), true, true);
+      DataPartition dataPartition =
+          partitionFetcher.getDataPartitionWithUnclosedTimeRange(
+              Collections.singletonMap(db, Collections.singletonList(queryParam)));
+      List<TRegionReplicaSet> regionReplicaSets =
+          dataPartition.getDataRegionReplicaSet(deviceId, Collections.emptyList());
+
+      // no schema
+      if (regionReplicaSets.isEmpty()
+          || regionReplicaSets.size() == 1 && NOT_ASSIGNED == regionReplicaSets.get(0)) {
+        TSExecuteStatementResp resp =
+            createResponse(DatasetHeaderFactory.getLastQueryHeader(), queryId);
+        resp.setStatus(RpcUtils.getStatus(TSStatusCode.SUCCESS_STATUS, ""));
+        resp.setQueryResult(Collections.emptyList());
+        finished = true;
+        resp.setMoreData(true);
+        return resp;
+      }
+
+      TEndPoint lastRegionLeader =
+          regionReplicaSets
+              .get(regionReplicaSets.size() - 1)
+              .dataNodeLocations
+              .get(0)
+              .mPPDataExchangeEndPoint;
+      // the device's all dataRegion's leader are on the same node, may can read directly from cache
+      if (isSameNode(lastRegionLeader)) {
+        boolean canUseNullEntry =
+            regionReplicaSets.stream()
+                .limit(regionReplicaSets.size() - 1L)
+                .allMatch(
+                    regionReplicaSet ->
+                        regionReplicaSet
+                            .dataNodeLocations
+                            .get(0)
+                            .mPPDataExchangeEndPoint
+                            .equals(lastRegionLeader));
+        int sensorNum = req.sensors.size();
+        TsBlockBuilder builder = LastQueryUtil.createTsBlockBuilder(sensorNum);
+        boolean allCached = true;
+        for (String sensor : req.sensors) {
+          PartialPath fullPath;
+          if (req.isLegalPathNodes()) {
+            fullPath = devicePath.concatNode(sensor);
+          } else {
+            fullPath = devicePath.concatNode((new PartialPath(sensor)).getFullPath());
+          }
+          TimeValuePair timeValuePair = DATA_NODE_SCHEMA_CACHE.getLastCache(fullPath);
+          if (timeValuePair == null) {
+            allCached = false;
+            break;
+          } else if (timeValuePair.getValue() == null) {
+            // there is no data for this sensor
+            if (!canUseNullEntry) {
+              allCached = false;
+              break;
+            }
+          } else {
+            // we don't consider TTL
+            LastQueryUtil.appendLastValue(
+                builder,
+                timeValuePair.getTimestamp(),
+                new Binary(fullPath.getFullPath()),
+                timeValuePair.getValue().getStringValue(),
+                timeValuePair.getValue().getDataType().name());
+          }
+        }
+        // cache hit
+        if (allCached) {
+          TSExecuteStatementResp resp =
+              createResponse(DatasetHeaderFactory.getLastQueryHeader(), queryId);
+          resp.setStatus(RpcUtils.getStatus(TSStatusCode.SUCCESS_STATUS, ""));
+          if (builder.isEmpty()) {
+            resp.setQueryResult(Collections.emptyList());
+          } else {
+            resp.setQueryResult(Collections.singletonList(serde.serialize(builder.build())));
+          }
+          finished = true;
+          resp.setMoreData(true);
+          return resp;
+        }
+      }
+
+      // cache miss
+      Statement s = StatementGenerator.createStatement(convert(req), clientSession.getZoneId());
+      // permission check
+      TSStatus status = AuthorityChecker.checkAuthority(s, clientSession);
+      if (status.getCode() != TSStatusCode.SUCCESS_STATUS.getStatusCode()) {
+        return RpcUtils.getTSExecuteStatementResp(status);
+      }
+
+      quota =
+          DataNodeThrottleQuotaManager.getInstance()
+              .checkQuota(SESSION_MANAGER.getCurrSession().getUsername(), s);
+
+      if (ENABLE_AUDIT_LOG) {
+        AuditLogger.log(String.format("Last Data Query: %s", req), s);
+      }
+      // create and cache dataset
+      ExecutionResult result =
+          COORDINATOR.execute(
+              s,
+              queryId,
+              SESSION_MANAGER.getSessionInfo(clientSession),
+              "",
+              partitionFetcher,
+              schemaFetcher,
+              req.getTimeout());
+
+      if (result.status.code != TSStatusCode.SUCCESS_STATUS.getStatusCode()) {
+        throw new RuntimeException("error code: " + result.status);
+      }
+
+      IQueryExecution queryExecution = COORDINATOR.getQueryExecution(queryId);
+
+      try (SetThreadName threadName = new SetThreadName(result.queryId.getId())) {
+        TSExecuteStatementResp resp;
+        if (queryExecution.isQuery()) {
+          resp = createResponse(queryExecution.getDatasetHeader(), queryId);
+          TSStatus tsstatus = new TSStatus();
+          tsstatus.setCode(TSStatusCode.REDIRECTION_RECOMMEND.getStatusCode());
+          tsstatus.setRedirectNode(lastRegionLeader);
+          resp.setStatus(tsstatus);
+          finished = SELECT_RESULT.apply(resp, queryExecution, req.fetchSize);
+          resp.setMoreData(!finished);
+          quota.addReadResult(resp.getQueryResult());
+        } else {
+          resp = RpcUtils.getTSExecuteStatementResp(result.status);
+        }
+        return resp;
+      }
+
+    } catch (Exception e) {
+      finished = true;
+      t = e;
+      return RpcUtils.getTSExecuteStatementResp(
+          onQueryException(e, "\"" + req + "\". " + OperationType.EXECUTE_LAST_DATA_QUERY));
+    } catch (Error error) {
+      t = error;
+      throw error;
+    } finally {
+      COORDINATOR.recordExecutionTime(queryId, System.currentTimeMillis() - startTime);
+      if (finished) {
+        addStatementExecutionLatency(
+            OperationType.EXECUTE_LAST_DATA_QUERY,
+            StatementType.QUERY,
+            System.nanoTime() - startNanoTime);
+        COORDINATOR.cleanupQueryExecution(queryId, t);
+      }

Review Comment:
   refer to other interface, change here.



##########
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/thrift/impl/ClientRPCServiceImpl.java:
##########
@@ -583,6 +601,207 @@ public TSExecuteStatementResp executeLastDataQueryV2(TSLastDataQueryReq req) {
     return executeLastDataQueryInternal(req, SELECT_RESULT);
   }
 
+  @Override
+  public TSExecuteStatementResp executeFastLastDataQueryForOneDeviceV2(
+      TSFastLastDataQueryForOneDeviceReq req) {
+    boolean finished = false;
+    long queryId = Long.MIN_VALUE;
+    IClientSession clientSession = SESSION_MANAGER.getCurrSessionAndUpdateIdleTime();
+    OperationQuota quota = null;
+    if (!SESSION_MANAGER.checkLogin(clientSession)) {
+      return RpcUtils.getTSExecuteStatementResp(getNotLoggedInStatus());
+    }
+    long startTime = System.currentTimeMillis();
+    long startNanoTime = System.nanoTime();
+    Throwable t = null;
+    try {
+      String db;
+      String deviceId;
+      PartialPath devicePath;
+
+      queryId = SESSION_MANAGER.requestQueryId(clientSession, req.statementId);
+
+      if (req.isLegalPathNodes()) {
+        db = req.db;
+        deviceId = req.deviceId;
+        devicePath = new PartialPath(deviceId.split("\\."));
+      } else {
+        db = new PartialPath(req.db).getFullPath();
+        devicePath = new PartialPath(req.deviceId);
+        deviceId = devicePath.getFullPath();
+      }
+
+      DataPartitionQueryParam queryParam =
+          new DataPartitionQueryParam(deviceId, Collections.emptyList(), true, true);
+      DataPartition dataPartition =
+          partitionFetcher.getDataPartitionWithUnclosedTimeRange(
+              Collections.singletonMap(db, Collections.singletonList(queryParam)));
+      List<TRegionReplicaSet> regionReplicaSets =
+          dataPartition.getDataRegionReplicaSet(deviceId, Collections.emptyList());
+
+      // no schema
+      if (regionReplicaSets.isEmpty()
+          || regionReplicaSets.size() == 1 && NOT_ASSIGNED == regionReplicaSets.get(0)) {
+        TSExecuteStatementResp resp =
+            createResponse(DatasetHeaderFactory.getLastQueryHeader(), queryId);
+        resp.setStatus(RpcUtils.getStatus(TSStatusCode.SUCCESS_STATUS, ""));
+        resp.setQueryResult(Collections.emptyList());
+        finished = true;
+        resp.setMoreData(true);
+        return resp;
+      }
+
+      TEndPoint lastRegionLeader =
+          regionReplicaSets
+              .get(regionReplicaSets.size() - 1)
+              .dataNodeLocations
+              .get(0)
+              .mPPDataExchangeEndPoint;
+      // the device's all dataRegion's leader are on the same node, may can read directly from cache
+      if (isSameNode(lastRegionLeader)) {
+        boolean canUseNullEntry =
+            regionReplicaSets.stream()
+                .limit(regionReplicaSets.size() - 1L)
+                .allMatch(
+                    regionReplicaSet ->
+                        regionReplicaSet
+                            .dataNodeLocations
+                            .get(0)
+                            .mPPDataExchangeEndPoint
+                            .equals(lastRegionLeader));

Review Comment:
   use `isSameNode` method.



##########
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/thrift/impl/ClientRPCServiceImpl.java:
##########
@@ -583,6 +601,207 @@ public TSExecuteStatementResp executeLastDataQueryV2(TSLastDataQueryReq req) {
     return executeLastDataQueryInternal(req, SELECT_RESULT);
   }
 
+  @Override
+  public TSExecuteStatementResp executeFastLastDataQueryForOneDeviceV2(
+      TSFastLastDataQueryForOneDeviceReq req) {
+    boolean finished = false;
+    long queryId = Long.MIN_VALUE;
+    IClientSession clientSession = SESSION_MANAGER.getCurrSessionAndUpdateIdleTime();
+    OperationQuota quota = null;
+    if (!SESSION_MANAGER.checkLogin(clientSession)) {
+      return RpcUtils.getTSExecuteStatementResp(getNotLoggedInStatus());
+    }
+    long startTime = System.currentTimeMillis();
+    long startNanoTime = System.nanoTime();
+    Throwable t = null;
+    try {
+      String db;
+      String deviceId;
+      PartialPath devicePath;
+
+      queryId = SESSION_MANAGER.requestQueryId(clientSession, req.statementId);
+
+      if (req.isLegalPathNodes()) {
+        db = req.db;
+        deviceId = req.deviceId;
+        devicePath = new PartialPath(deviceId.split("\\."));
+      } else {
+        db = new PartialPath(req.db).getFullPath();
+        devicePath = new PartialPath(req.deviceId);
+        deviceId = devicePath.getFullPath();
+      }
+
+      DataPartitionQueryParam queryParam =
+          new DataPartitionQueryParam(deviceId, Collections.emptyList(), true, true);
+      DataPartition dataPartition =
+          partitionFetcher.getDataPartitionWithUnclosedTimeRange(
+              Collections.singletonMap(db, Collections.singletonList(queryParam)));
+      List<TRegionReplicaSet> regionReplicaSets =
+          dataPartition.getDataRegionReplicaSet(deviceId, Collections.emptyList());
+
+      // no schema
+      if (regionReplicaSets.isEmpty()
+          || regionReplicaSets.size() == 1 && NOT_ASSIGNED == regionReplicaSets.get(0)) {
+        TSExecuteStatementResp resp =
+            createResponse(DatasetHeaderFactory.getLastQueryHeader(), queryId);
+        resp.setStatus(RpcUtils.getStatus(TSStatusCode.SUCCESS_STATUS, ""));
+        resp.setQueryResult(Collections.emptyList());
+        finished = true;
+        resp.setMoreData(true);
+        return resp;
+      }
+
+      TEndPoint lastRegionLeader =
+          regionReplicaSets
+              .get(regionReplicaSets.size() - 1)
+              .dataNodeLocations
+              .get(0)
+              .mPPDataExchangeEndPoint;
+      // the device's all dataRegion's leader are on the same node, may can read directly from cache
+      if (isSameNode(lastRegionLeader)) {
+        boolean canUseNullEntry =

Review Comment:
   add comments for this one to explain in which case, we cannot use NullCacheEntry from current node.



##########
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/thrift/impl/ClientRPCServiceImpl.java:
##########
@@ -583,6 +601,207 @@ public TSExecuteStatementResp executeLastDataQueryV2(TSLastDataQueryReq req) {
     return executeLastDataQueryInternal(req, SELECT_RESULT);
   }
 
+  @Override
+  public TSExecuteStatementResp executeFastLastDataQueryForOneDeviceV2(
+      TSFastLastDataQueryForOneDeviceReq req) {
+    boolean finished = false;
+    long queryId = Long.MIN_VALUE;
+    IClientSession clientSession = SESSION_MANAGER.getCurrSessionAndUpdateIdleTime();
+    OperationQuota quota = null;
+    if (!SESSION_MANAGER.checkLogin(clientSession)) {
+      return RpcUtils.getTSExecuteStatementResp(getNotLoggedInStatus());
+    }
+    long startTime = System.currentTimeMillis();
+    long startNanoTime = System.nanoTime();
+    Throwable t = null;
+    try {
+      String db;
+      String deviceId;
+      PartialPath devicePath;
+
+      queryId = SESSION_MANAGER.requestQueryId(clientSession, req.statementId);
+
+      if (req.isLegalPathNodes()) {
+        db = req.db;
+        deviceId = req.deviceId;
+        devicePath = new PartialPath(deviceId.split("\\."));
+      } else {
+        db = new PartialPath(req.db).getFullPath();
+        devicePath = new PartialPath(req.deviceId);
+        deviceId = devicePath.getFullPath();
+      }
+
+      DataPartitionQueryParam queryParam =
+          new DataPartitionQueryParam(deviceId, Collections.emptyList(), true, true);
+      DataPartition dataPartition =
+          partitionFetcher.getDataPartitionWithUnclosedTimeRange(
+              Collections.singletonMap(db, Collections.singletonList(queryParam)));
+      List<TRegionReplicaSet> regionReplicaSets =
+          dataPartition.getDataRegionReplicaSet(deviceId, Collections.emptyList());
+
+      // no schema
+      if (regionReplicaSets.isEmpty()
+          || regionReplicaSets.size() == 1 && NOT_ASSIGNED == regionReplicaSets.get(0)) {
+        TSExecuteStatementResp resp =
+            createResponse(DatasetHeaderFactory.getLastQueryHeader(), queryId);
+        resp.setStatus(RpcUtils.getStatus(TSStatusCode.SUCCESS_STATUS, ""));
+        resp.setQueryResult(Collections.emptyList());
+        finished = true;
+        resp.setMoreData(true);
+        return resp;
+      }
+
+      TEndPoint lastRegionLeader =
+          regionReplicaSets
+              .get(regionReplicaSets.size() - 1)
+              .dataNodeLocations
+              .get(0)
+              .mPPDataExchangeEndPoint;
+      // the device's all dataRegion's leader are on the same node, may can read directly from cache

Review Comment:
   ```suggestion
         // the device's dataRegion's leader of latest time partiton is on current node, may can read directly from cache
   ```



-- 
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