使用查询说明

借助 Query Explain,您可以将 Datastore 模式查询提交到后端,这样就可以收到有关后端查询执行的详细性能统计信息。其功能类似于许多关系型数据库系统中 EXPLAIN ANALYZE 操作。

您可以使用 Datastore 模式客户端库发送 Query Explain 请求。

“Query Explain”结果可帮助您了解如何执行查询,向您展示效率低下的问题以及可能存在的服务器端瓶颈的位置。

查询说明:

  • 提供有关规划阶段的数据分析,以便您调整查询索引并提高效率。
  • 帮助您了解每个查询的费用和性能,并且让您可以快速遍历不同的查询模式,以优化其使用情况。

了解 Query Explain 选项:默认和分析

您可以使用 default 选项或 analyze 选项执行 Query Explain 操作。

使用默认选项时,Query Explain 会规划查询,但会跳过执行阶段。这样将返回规划师阶段信息。您可以使用此参数来检查查询是否具有必要的索引,并了解使用了哪些索引。这可帮助您验证,例如,特定查询是否使用了复合索引,而不是与许多不同的索引进行交集。

借助 analytics 选项,Query Explain 同时执行这两个计划并执行查询。这将返回前面提到的所有规划工具信息,以及来自查询执行运行时的统计信息。其中包括结算信息以及有关查询执行情况的系统级数据分析。您可以使用此工具测试各种查询和索引配置,以优化其费用和延迟时间。

Query Explain 如何收费?

使用默认选项说明查询时,系统不会执行任何索引或读取操作。无论查询复杂程度如何,一次读取操作都会产生费用。

使用分析选项解释查询时,系统会执行索引和读取操作,因此您需要照常为查询付费。分析活动不会产生额外费用,只需按正在执行的查询通常收费。

使用默认选项执行查询

您可以使用客户端库来提交默认选项请求。

请注意,查询说明结果通过 Identity and Access Management 进行身份验证,与常规查询操作相同。

Java

如需了解如何安装和使用 Datastore 模式客户端库,请参阅 Datastore 模式客户端库。 如需了解详情,请参阅 Datastore 模式 Java API 参考文档

如需向 Datastore 模式进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证


import com.google.cloud.datastore.Datastore;
import com.google.cloud.datastore.DatastoreOptions;
import com.google.cloud.datastore.Entity;
import com.google.cloud.datastore.Query;
import com.google.cloud.datastore.QueryResults;
import com.google.cloud.datastore.models.ExplainMetrics;
import com.google.cloud.datastore.models.ExplainOptions;
import com.google.cloud.datastore.models.PlanSummary;
import java.util.List;
import java.util.Map;
import java.util.Optional;

public class QueryProfileExplain {
  public static void invoke() throws Exception {
    // Instantiates a client
    Datastore datastore = DatastoreOptions.getDefaultInstance().getService();

    // Build the query
    Query<Entity> query = Query.newEntityQueryBuilder().setKind("Task").build();

    // Set the explain options to get back *only* the plan summary
    QueryResults<Entity> results = datastore.run(query, ExplainOptions.newBuilder().build());

    // Get the explain metrics
    Optional<ExplainMetrics> explainMetrics = results.getExplainMetrics();
    if (!explainMetrics.isPresent()) {
      throw new Exception("No explain metrics returned");
    }
    PlanSummary planSummary = explainMetrics.get().getPlanSummary();
    List<Map<String, Object>> indexesUsed = planSummary.getIndexesUsed();
    System.out.println("----- Indexes Used -----");
    indexesUsed.forEach(map -> map.forEach((key, val) -> System.out.println(key + ": " + val)));
  }
}

请查看响应中的 indexes_used 字段,了解查询计划中使用的索引:

"indexes_used": [
        {"query_scope": "Collection Group", "properties": "(__name__ ASC)"},
]

如需详细了解该报告,请参阅报告参考文档

使用分析选项执行查询

您可以使用客户端库来提交默认选项请求。

请注意,查询分析结果通过 Identity and Access Management (IAM) 进行身份验证,与常规查询操作相同。

Java

如需了解如何安装和使用 Datastore 模式客户端库,请参阅 Datastore 模式客户端库。 如需了解详情,请参阅 Datastore 模式 Java API 参考文档

如需向 Datastore 模式进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

import com.google.cloud.datastore.Datastore;
import com.google.cloud.datastore.DatastoreOptions;
import com.google.cloud.datastore.Entity;
import com.google.cloud.datastore.Query;
import com.google.cloud.datastore.QueryResults;
import com.google.cloud.datastore.models.ExecutionStats;
import com.google.cloud.datastore.models.ExplainMetrics;
import com.google.cloud.datastore.models.ExplainOptions;
import com.google.cloud.datastore.models.PlanSummary;
import java.util.List;
import java.util.Map;

public class QueryProfileExplainAnalyze {
  public static void invoke() throws Exception {
    // Instantiates a client
    Datastore datastore = DatastoreOptions.getDefaultInstance().getService();

    // Build the query
    Query<Entity> query = Query.newEntityQueryBuilder().setKind("Task").build();

    // Set explain options with analzye = true to get back the query stats, plan info, and query
    // results
    QueryResults<Entity> results =
        datastore.run(query, ExplainOptions.newBuilder().setAnalyze(true).build());

    // Get the result set stats
    if (!results.getExplainMetrics().isPresent()) {
      throw new Exception("No explain metrics returned");
    }
    ExplainMetrics explainMetrics = results.getExplainMetrics().get();

    // Get the execution stats
    if (!explainMetrics.getExecutionStats().isPresent()) {
      throw new Exception("No execution stats returned");
    }

    ExecutionStats executionStats = explainMetrics.getExecutionStats().get();
    Map<String, Object> debugStats = executionStats.getDebugStats();
    System.out.println("----- Debug Stats -----");
    debugStats.forEach((key, val) -> System.out.println(key + ": " + val));
    System.out.println("----------");

    long resultsReturned = executionStats.getResultsReturned();
    System.out.println("Results returned: " + resultsReturned);

    // Get the plan summary
    PlanSummary planSummary = explainMetrics.getPlanSummary();
    List<Map<String, Object>> indexesUsed = planSummary.getIndexesUsed();
    System.out.println("----- Indexes Used -----");
    indexesUsed.forEach(map -> map.forEach((key, val) -> System.out.println(key + ": " + val)));

    if (!results.hasNext()) {
      throw new Exception("query yielded no results");
    }

    // Get the query results
    System.out.println("----- Query Results -----");
    while (results.hasNext()) {
      Entity entity = results.next();
      System.out.printf("Entity: %s%n", entity);
    }
  }
}

请参阅 executionStats 对象,查找查询性能分析信息,例如:

{
    "resultsReturned": "5",
    "executionDuration": "0.100718s",
    "readOperations": "5",
    "debugStats": {
               "index_entries_scanned": "95000",
               "documents_scanned": "5"
               "billing_details": {
                     "documents_billable": "5",
                     "index_entries_billable": "0",
                     "small_ops": "0",
                     "min_query_cost": "0",
               }
    }
}

如需详细了解该报告,请参阅报告参考文档

解读结果并进行调整

以下示例场景按类型和制作国家/地区查询电影,并演示了如何优化查询使用的索引。

如需详细了解该报告,请参阅“查询说明”报告参考文档

为便于说明,我们假设此 SQL 查询等效于此查询。

SELECT *
FROM movies
WHERE category = 'Romantic' AND country = 'USA';

如果我们使用“Analyze”选项,以下报告输出将显示查询针对单字段索引 (category ASC, __name__ ASC)(country ASC, __name__ ASC) 运行。它会扫描 16,500 个索引条目,但仅返回 1,200 个文档。

// Output query planning info
"indexes_used": [
    {"query_scope": "Collection Group", "properties": "(category ASC, __name__ ASC)"},
    {"query_scope": "Collection Group", "properties": "(country ASC, __name__ ASC)"},
]

// Output query status
{
    "resultsReturned": "1200",
    "executionDuration": "0.118882s",
    "readOperations": "1200",
    "debugStats": {
               "index_entries_scanned": "16500",
               "documents_scanned": "1200"
               "billing_details": {
                     "documents_billable": "1200",
                     "index_entries_billable": "0",
                     "small_ops": "0",
                     "min_query_cost": "0",
               }
    }
}

为了优化执行查询的性能,您可以创建完全覆盖的复合索引(类别 ASC、国家/地区 ASC、__name__ ASC)。

如果再次在分析模式下运行查询,我们可以看到为此查询选择了新创建的索引,并且该查询的运行速度更快、效率更高。

// Output query planning info
    "indexes_used": [
        {"query_scope": "Collection Group", "properties": "(category ASC, country ASC, __name__ ASC)"}
        ]

// Output query stats
{
    "resultsReturned": "1200",
    "executionDuration": "0.026139s",
    "readOperations": "1200",
    "debugStats": {
               "index_entries_scanned": "1200",
               "documents_scanned": "1200"
               "billing_details": {
                     "documents_billable": "1200",
                     "index_entries_billable": "0",
                     "small_ops": "0",
                     "min_query_cost": "0",
               }
    }
}

后续步骤