diff --git a/.github/scripts/release.sh b/.github/scripts/release.sh new file mode 100755 index 000000000..337b30f82 --- /dev/null +++ b/.github/scripts/release.sh @@ -0,0 +1,34 @@ +## this script is to update for major/minor updates +## the input version format should be like: 1.0 or 0.12 +VERSION=$1 + +echo "Processing variables" +cp variables/variables-nightly.ts variables/variables-$VERSION.ts +sed -i "s/greptimedbVersion: 'v[^']*'/greptimedbVersion: 'v$VERSION.0'/" variables/variables-$VERSION.ts +sed -i "s/greptimedbVersion: 'v[^']*'/greptimedbVersion: 'v$VERSION.0'/" variables/variables-nightly.ts + +echo "Processing localized sidebars" +cp i18n/zh/docusaurus-plugin-content-docs/current.json i18n/zh/docusaurus-plugin-content-docs/version-$VERSION.json +jq 'del(.["version.label"])' i18n/zh/docusaurus-plugin-content-docs/version-$VERSION.json > temp.json && mv temp.json i18n/zh/docusaurus-plugin-content-docs/version-$VERSION.json + +echo "Removing greptimecloud content from current version" +CURRENT_VERSION=$(jq -r '.[0]' versions.json) +rm -rf versioned_docs/version-$CURRENT_VERSION/greptimecloud +rm -rf i18n/zh/docusaurus-plugin-content-docs/version-$CURRENT_VERSION/greptimecloud +jq 'del(.docs[] | select(.label == "GreptimeCloud"))' versioned_sidebars/version-$CURRENT_VERSION-sidebars.json > temp.json && mv temp.json versioned_sidebars/version-$CURRENT_VERSION-sidebars.json +sed -i '/^- \[GreptimeCloud\]/d' versioned_docs/version-$CURRENT_VERSION/index.md +sed -i '/^- \[GreptimeCloud\]/d' i18n/zh/docusaurus-plugin-content-docs/version-$CURRENT_VERSION/index.md + +echo "Generating new version" +npm run docusaurus docs:version $VERSION + +echo "Removing oldest version" +OLDEST_VERSION=$(jq -r '.[-1]' versions.json) +rm -rf versioned_docs/version-$OLDEST_VERSION +rm -rf i18n/zh/docusaurus-plugin-content-docs/version-$OLDEST_VERSION/ +rm i18n/zh/docusaurus-plugin-content-docs/version-$OLDEST_VERSION.json +rm versioned_sidebars/version-$OLDEST_VERSION-sidebars.json +jq '.[:-1]' versions.json > temp.json && mv temp.json versions.json + +# echo "Set new default" +# npm run docusaurus docs:use-version $VERSION diff --git a/.github/workflows/bump-version.yml b/.github/workflows/bump-version.yml new file mode 100644 index 000000000..5a91a5302 --- /dev/null +++ b/.github/workflows/bump-version.yml @@ -0,0 +1,39 @@ +name: Version Docs + +on: + workflow_dispatch: + inputs: + version: + description: 'Version number without patch (e.g., 1.0 or 0.12)' + required: true + type: string + +jobs: + update-docs: + runs-on: ubuntu-latest + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Set up Node.js + uses: actions/setup-node@v3 + with: + node-version: 22 + + - name: Install dependencies + run: npm install + + - name: Call update scripts + run: | + VERSION=${{ github.event.inputs.version }} + .github/scripts/release.sh $VERSION + + - name: Create Pull Request + uses: peter-evans/create-pull-request@v5 + with: + commit-message: "Version docs to ${{ github.event.inputs.version }}" + title: "Version docs to ${{ github.event.inputs.version }}" + body: "This PR updates the docs to version ${{ github.event.inputs.version }}." + branch: "version-docs-${{ github.event.inputs.version }}" + base: main + delete-branch: true diff --git a/docusaurus.config.ts b/docusaurus.config.ts index 30018ddd4..3dd0a4d9c 100644 --- a/docusaurus.config.ts +++ b/docusaurus.config.ts @@ -135,12 +135,6 @@ const config: Config = { current: { label: 'nightly', path: 'nightly', - }, - '0.8': { - path: 'v0.8' - }, - '0.7': { - path: 'v0.7' } }, remarkPlugins: [ diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7.json b/i18n/zh/docusaurus-plugin-content-docs/version-0.12.json similarity index 71% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7.json rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12.json index 58d3ffed5..3488b72ce 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.7.json +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12.json @@ -15,10 +15,6 @@ "message": "概念", "description": "The label for category Concepts in sidebar docs" }, - "sidebar.docs.category.Clients": { - "message": "客户端", - "description": "The label for category Clients in sidebar docs" - }, "sidebar.docs.category.Migrate to GreptimeDB": { "message": "迁移到 GreptimeDB", "description": "The label for category Migrate to GreptimeDB in sidebar docs" @@ -31,9 +27,9 @@ "message": "读取数据", "description": "The label for category Query Data in sidebar docs" }, - "sidebar.docs.category.Continuous Aggregation": { - "message": "持续聚合", - "description": "The label for category Continuous Aggregation in sidebar docs" + "sidebar.docs.category.Flow Computation": { + "message": "流计算", + "description": "The label for category Flow Computation in sidebar docs" }, "sidebar.docs.category.Logs": { "message": "日志", @@ -43,14 +39,26 @@ "message": "客户端库", "description": "The label for category Client Libraries in sidebar docs" }, - "sidebar.docs.category.Operations": { - "message": "运维操作", + "sidebar.docs.category.Administration": { + "message": "管理", "description": "The label for category Operations in sidebar docs" }, + "sidebar.docs.category.Authentication": { + "message": "鉴权", + "description": "The label for category Authentication in sidebar docs" + }, + "sidebar.docs.category.Deployments": { + "message": "部署", + "description": "The label for category Deployments in sidebar docs" + }, "sidebar.docs.category.Deploy on Kubernetes": { "message": "部署到 Kubernetes", "description": "The label for category Deploy on Kubernetes in sidebar docs" }, + "sidebar.docs.category.Manage GreptimeDB Operator": { + "message": "管理 GreptimeDB Operator", + "description": "The label for category Deploy on Kubernetes in sidebar docs" + }, "sidebar.docs.category.Disaster Recovery": { "message": "灾难恢复", "description": "The label for category Disaster Recovery in sidebar docs" @@ -91,6 +99,10 @@ "message": "监控 Host Metrics", "description": "The label for category Monitor Host Metrics in sidebar docs" }, + "sidebar.docs.category.GreptimeDB Enterprise": { + "message": "GreptimeDB 企业版", + "description": "The label for category GreptimeDB Enterprise in sidebar docs" + }, "sidebar.docs.category.Reference": { "message": "Reference", "description": "The label for category Reference in sidebar docs" @@ -143,16 +155,36 @@ "message": "Release Notes", "description": "The label for link Release Notes in sidebar docs, linking to /release-notes" }, - "version.label": { - "message": "0.7", - "description": "The label for version 0.7" + "sidebar.docs.category.Ingest Data": { + "message": "写入数据", + "description": "The label for category Ingest Data in sidebar docs" + }, + "sidebar.docs.category.For Observerbility": { + "message": "可观测场景", + "description": "The label for category For Observerbility in sidebar docs" + }, + "sidebar.docs.category.For IoT": { + "message": "物联网(IoT)场景", + "description": "The label for category For IoT in sidebar docs" + }, + "sidebar.docs.category.gRPC SDKs": { + "message": "gRPC SDKs", + "description": "The label for category gRPC SDKs in sidebar docs" + }, + "sidebar.docs.category.Manage Data": { + "message": "管理数据", + "description": "The label for category Manage Data in sidebar docs" + }, + "sidebar.docs.category.Protocols": { + "message": "协议", + "description": "The label for category Manage Data in sidebar docs" }, - "sidebar.docs.category.Quick Start": { - "message": "快速开始", - "description": "The label for category Quick Start in sidebar docs" + "sidebar.docs.category.Monitoring": { + "message": "监控", + "description": "The label for category Monitoring in sidebar docs" }, - "sidebar.docs.category.Benchmarks": { - "message": "Benchmarks", - "description": "The label for category Benchmarks in sidebar docs" + "sidebar.docs.category.Vector Storage": { + "message": "向量存储", + "description": "The label for category Vector Storage in sidebar docs" } } diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/contributor-guide/datanode/data-persistence-indexing.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/datanode/data-persistence-indexing.md similarity index 92% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7/contributor-guide/datanode/data-persistence-indexing.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/datanode/data-persistence-indexing.md index 3547cb4b2..7b4dcf2df 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/contributor-guide/datanode/data-persistence-indexing.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/datanode/data-persistence-indexing.md @@ -1,3 +1,8 @@ +--- +keywords: [数据持久化, 索引机制, SST 文件, 倒排索引] +description: 介绍了 GreptimeDB 的数据持久化和索引机制,包括 SST 文件格式、数据持久化过程和倒排索引的实现。 +--- + # 数据持久化与索引 与所有类似 LSMT 的存储引擎一样,MemTables 中的数据被持久化到耐久性存储,例如本地磁盘文件系统或对象存储服务。GreptimeDB 采用 [Apache Parquet][1] 作为其持久文件格式。 @@ -12,7 +17,7 @@ Parquet 具有层次结构,类似于“行组-列-数据页”。Parquet 文 其次,相同列的数据往往是同质的(比如具备近似的值),这有助于在采用字典和 Run-Length Encoding(RLE)等技术进行压缩。 -![Parquet file format](/parquet-file-format.png) +Parquet file format ## 数据持久化 @@ -23,7 +28,7 @@ GreptimeDB 提供了 `storage.flush.global_write_buffer_size` 的配置项来设 Apache Parquet 文件格式在列块和数据页的头部提供了内置的统计信息,用于剪枝和跳过。 -![Column chunk header](/column-chunk-header.png) +Column chunk header 例如,在上述 Parquet 文件中,如果你想要过滤 `name` 等于 `Emily` 的行,你可以轻松跳过行组 0,因为 `name` 字段的最大值是 `Charlie`。这些统计信息减少了 IO 操作。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/contributor-guide/datanode/metric-engine.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/datanode/metric-engine.md similarity index 93% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7/contributor-guide/datanode/metric-engine.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/datanode/metric-engine.md index 000e49c78..5fa0f6bb7 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/contributor-guide/datanode/metric-engine.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/datanode/metric-engine.md @@ -1,3 +1,8 @@ +--- +keywords: [Metric 引擎, 逻辑表, 物理表, DDL 操作] +description: 介绍了 Metric 引擎的概念、架构及设计,重点描述了逻辑表与物理表的区别和批量 DDL 操作的实现。 +--- + # Metric 引擎 ## 概述 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/contributor-guide/datanode/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/datanode/overview.md similarity index 88% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7/contributor-guide/datanode/overview.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/datanode/overview.md index ae81169d9..1f63a0dc7 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/contributor-guide/datanode/overview.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/datanode/overview.md @@ -1,3 +1,8 @@ +--- +keywords: [Datanode, gRPC 服务, HTTP 服务, Heartbeat Task, Region Manager] +description: 介绍了 Datanode 的主要职责和组件,包括 gRPC 服务、HTTP 服务、Heartbeat Task 和 Region Manager。 +--- + # Datanode ## Introduction diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/contributor-guide/datanode/python-scripts.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/datanode/python-scripts.md similarity index 88% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7/contributor-guide/datanode/python-scripts.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/datanode/python-scripts.md index 916bce481..831278e80 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/contributor-guide/datanode/python-scripts.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/datanode/python-scripts.md @@ -1,3 +1,8 @@ +--- +keywords: [Python 脚本, 数据分析, CPython, RustPython] +description: 介绍了在 GreptimeDB 中使用 Python 脚本进行数据分析的两种后端实现:CPython 和嵌入式 RustPython 解释器。 +--- + # Python 脚本 ## 简介 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/contributor-guide/datanode/query-engine.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/datanode/query-engine.md similarity index 93% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7/contributor-guide/datanode/query-engine.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/datanode/query-engine.md index 9a0f7ff5f..72b7a7f98 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/contributor-guide/datanode/query-engine.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/datanode/query-engine.md @@ -1,3 +1,8 @@ +--- +keywords: [查询引擎, DataFusion, 逻辑计划, 物理计划] +description: 介绍了 GreptimeDB 的查询引擎架构,基于 Apache DataFusion 构建,涵盖逻辑计划、物理计划、优化和执行过程。 +--- + # Query Engine ## 介绍 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/contributor-guide/datanode/storage-engine.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/datanode/storage-engine.md similarity index 78% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7/contributor-guide/datanode/storage-engine.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/datanode/storage-engine.md index 7a1a905c1..45301b4b8 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/contributor-guide/datanode/storage-engine.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/datanode/storage-engine.md @@ -1,3 +1,8 @@ +--- +keywords: [存储引擎, Mito, LSMT, 数据模型, Region] +description: 详细介绍了 GreptimeDB 的存储引擎架构、数据模型和 region 的概念,重点描述了 Mito 存储引擎的优化和组件。 +--- + # 存储引擎 ## 概述 @@ -52,6 +57,6 @@ tag-1, ..., tag-m, timestamp -> field-1, ..., field-n - field 列是可空的 - 数据按照 tag 列和 timestamp 列有序存储 -## 区域(Region) +## Region -数据在存储引擎中以 `region`(区域)的形式存储,`region` 是引擎中的一个逻辑隔离存储单元。`region` 中的行必须具有相同的 `schema`(模式),该 `schema` 定义了 `region` 中的 tag 列,timestamp 列和 field 列。数据库中表的数据存储在一到多个 `region` 中。 +数据在存储引擎中以 `region` 的形式存储,`region` 是引擎中的一个逻辑隔离存储单元。`region` 中的行必须具有相同的 `schema`(模式),该 `schema` 定义了 `region` 中的 tag 列,timestamp 列和 field 列。数据库中表的数据存储在一到多个 `region` 中。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/contributor-guide/datanode/wal.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/datanode/wal.md similarity index 76% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7/contributor-guide/datanode/wal.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/datanode/wal.md index b3b21b18b..7a6a455e1 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/contributor-guide/datanode/wal.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/datanode/wal.md @@ -1,3 +1,8 @@ +--- +keywords: [预写日志, WAL, 数据持久化, 同步刷盘, 异步刷盘] +description: 介绍了 GreptimeDB 的预写日志(WAL)机制,包括其命名空间、同步/异步刷盘策略和在数据节点重启时的重放功能。 +--- + # 预写日志 ## 介绍 @@ -12,7 +17,7 @@ ## 命名空间 -WAL 的命名空间用于区分来自不同 region 的条目。追加和读取操作必须提供一个命名空间。目前,区域 ID 被用作命名空间,因为每个区域都有一个在数据节点重新启动时需要重构的 MemTable。 +WAL 的命名空间用于区分来自不同 region 的条目。追加和读取操作必须提供一个命名空间。目前,region ID 被用作命名空间,因为每个 region 都有一个在数据节点重新启动时需要重构的 MemTable。 ## 同步/异步刷盘 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/flownode/arrangement.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/flownode/arrangement.md new file mode 100644 index 000000000..dd3b6de09 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/flownode/arrangement.md @@ -0,0 +1,18 @@ +--- +keywords: [Arrangement, 状态存储, 键值对] +description: 描述了 Arrangement 在数据流进程中的状态存储功能,包括键值对存储、查询和删除操作的实现。 +--- + +# Arrangement + +Arrangement 存储数据流进程中的状态,存储 flow 的更新流(stream)以供进一步查询和更新。 + +Arrangement 本质上存储的是带有时间戳的键值对。 +在内部,Arrangement 接收类似 `((Key Row, Value Row), timestamp, diff)` 的 tuple,并将其存储在内存中。 +你可以使用 `get(now: Timestamp, key: Row)` 查询某个时间的键值对。 +Arrangement 假定早于某个时间(也称为 Low Watermark)的所有内容都已被写入到 sink 表中,不会为其保留历史记录。 + +:::tip 注意 +Arrangement 允许通过将传入 tuple 的 `diff` 设置为 -1 来删除键。 +此外,如果已将行数据添加到 Arrangement 并且使用不同的值插入相同的键,则原始值将被新值覆盖。 +::: diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/flownode/dataflow.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/flownode/dataflow.md new file mode 100644 index 000000000..9d0792254 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/flownode/dataflow.md @@ -0,0 +1,18 @@ +--- +keywords: [Dataflow, SQL 查询, 执行计划, 数据流, map, reduce] +description: 解释了 Dataflow 模块的核心计算功能,包括 SQL 查询转换、内部执行计划、数据流的触发运行和支持的操作。 +--- + +# 数据流 + +Dataflow 模块(参见 `flow::compute` 模块)是 `flow` 的核心计算模块。 +它接收 SQL 查询并将其转换为 `flow` 的内部执行计划。 +然后,该执行计划被转化为实际的数据流,而数据流本质上是一个由带有输入和输出端口的函数组成的有向无环图(DAG)。 +数据流会在需要时被触发运行。 + +目前该数据流只支持 `map`和 `reduce` 操作,未来将添加对 `join` 等操作的支持。 + +在内部,数据流使用 `tuple(row, time, diff)` 以行格式处理数据。 +这里 `row` 表示实际传递的数据,可能包含多个 `value` 对象。 +`time` 是系统时间,用于跟踪数据流的进度,`diff` 通常表示行的插入或删除(+1 或 -1)。 +因此,`tuple` 表示给定系统时间的 `row` 的插入/删除操作。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/flownode/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/flownode/overview.md new file mode 100644 index 000000000..ba78bd625 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/flownode/overview.md @@ -0,0 +1,21 @@ +--- +keywords: [Flownode, 流处理, FlownodeManager, FlowWorker] +description: 介绍了 Flownode 的基本概念、组件和当前版本的支持情况,包括 FlownodeManager、FlowWorker 和 Flow 的功能。 +--- + +# 概述 + +## 简介 + +`Flownode` 为数据库提供了一种简单的流处理(称为 `flow`)能力。 +`Flownode` 管理 `flow`,这些 `flow` 是从 `source` 接收数据并将数据发送到 `sink` 的任务。 + +在当前版本中,`Flownode` 仅在单机模式中支持,未来将支持分布式模式。 + +## 组件 + +`Flownode` 包含了 flow 流式处理的所有组件,以下是关键部分: + +- `FlownodeManager`:用于接收从 `Frontend` 转发的插入数据并将结果发送回 flow 的 sink 表。 +- 一定数量的 `FlowWorker` 实例,每个实例在单独的线程中运行。当前在单机模式中只有一个 flow worker,但这可能会在未来发生变化。 +- `Flow` 是一个主动从 `source` 接收数据并将数据发送到 `sink` 的任务。由 `FlownodeManager` 管理并由 `FlowWorker` 运行。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/contributor-guide/frontend/distributed-querying.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/frontend/distributed-querying.md similarity index 93% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7/contributor-guide/frontend/distributed-querying.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/frontend/distributed-querying.md index ef112cd58..ed47e5595 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/contributor-guide/frontend/distributed-querying.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/frontend/distributed-querying.md @@ -1,3 +1,8 @@ +--- +keywords: [分布式查询, 查询拆分, 查询合并, TableScan, 物理计划] +description: 介绍 GreptimeDB 中的分布式查询方法,包括查询的拆分和合并过程,以及 TableScan 节点的作用。 +--- + # 分布式查询 我们知道在 GreptimeDB 中数据是如何分布的(参见“[表分片][1]”),那么如何查询呢?在 GreptimeDB 中,分布式查询非常简单。简单来说,我们只需将查询拆分为子查询,每个子查询负责查询表数据的一个部分,然后将所有结果合并为最终结果。这是一种典型的“拆分-合并”方法。具体来说,让我们从查询到达 `frontend` 开始。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/contributor-guide/frontend/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/frontend/overview.md similarity index 73% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7/contributor-guide/frontend/overview.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/frontend/overview.md index 830aac09f..a1a0b3eb0 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/contributor-guide/frontend/overview.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/frontend/overview.md @@ -1,3 +1,8 @@ +--- +keywords: [Frontend, 客户端请求, 租户管理, 鉴权认证, 流量控制] +description: 介绍 GreptimeDB 中 Frontend 的功能和部署。 +--- + # 概述 `Frontend` 执行客户端的请求,也处理云服务中的一些特定任务,例如租户管理、鉴权认证、流量控制等。 @@ -13,6 +18,6 @@ - [表分片][2] - [分布式查询][3] -[1]: /user-guide/clients/overview.md +[1]: /user-guide/protocols/overview.md [2]: ./table-sharding.md [3]: ./distributed-querying.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/contributor-guide/frontend/table-sharding.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/frontend/table-sharding.md similarity index 62% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7/contributor-guide/frontend/table-sharding.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/frontend/table-sharding.md index 8315ab7d4..6f485edae 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/contributor-guide/frontend/table-sharding.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/frontend/table-sharding.md @@ -1,49 +1,15 @@ +--- +keywords: [表分片, 分区, Region, 数据存储, Region 自动移动] +description: 介绍 GreptimeDB 中表数据的分片方法,包括分区和 Region 的定义及其关系。 +--- + # 表分片 对于任何分布式数据库来说,数据的分片都是必不可少的。本文将描述 GreptimeDB 中的表数据如何进行分片。 ## 分区 -从逻辑上说,在 GreptimeDB 中数据是使用分区进行分片的。我们借用了在 OLTP 数据库中常用的概念“分区”,因为 GreptimeDB 使用“表”来组织数据并使用 SQL 来查询它。 - -在 GreptimeDB 中,一张表可以通过多种方式横向分区,并且它使用与 MySQL 相同的分区类型(以及相应的语法)。目前,GreptimeDB 支持 “RANGE COLUMNS 分区”。 - -每个分区仅包含表中的一部分数据,并按某些列值范围进行分组。例如,我们可以使用这样的语法在 GreptimeDB 中对表进行分区: - -```sql -CREATE TABLE (...) -PARTITION ON COLUMNS () ( - -); -``` - -该语法主要包含两部分: -- `PARTITION ON COLUMNS` 后跟随一个使用逗号分隔的列名列表,用于指定哪些列可能会被用于分区。这里指定的分区列表仅作为“白名单”使用,实际上可能只有其中的一部分列会被用于分区。 -- `RULE LIST` 是一个包含多个分区规则的列表,每个规则都是一个分区名称和一个分区条件的组合。此处的表达式可使用 `=`,`!=`,`>`,`>=`,`<`,`<=`,`AND`, `OR`,列名和字面量。 - -下面是一个具体的例子: - -```sql -CREATE TABLE my_table ( - a INT PRIMARY KEY, - b STRING, - ts TIMESTAMP TIME INDEX, -) -PARTITION ON COLUMNS (a) ( - a < 10, - a >= 10 AND a < 20, - a >= 20, -); -``` - -我们在上面创建的 `my_table` 有 3 个分区。分别是包含了 "a < 10" 的行;包含了 "10 \<= a < 20" 的行;和 "a >= 20" 的所有行。 - -:::warning 重要 - -1. 所有分区的范围不能重叠。 -2. 用于分区的列必须是在 `ON COLUMNS` 中指定。 - -::: +有关创建分区表的语法,请参阅用户指南中的[表分片](/user-guide/administration/manage-data/table-sharding.md)部分。 ## Region diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/contributor-guide/getting-started.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/getting-started.md similarity index 62% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7/contributor-guide/getting-started.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/getting-started.md index f87cdf635..5730c389a 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/contributor-guide/getting-started.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/getting-started.md @@ -1,3 +1,8 @@ +--- +keywords: [编译, 运行, 源代码, 系统要求, 依赖项, Docker] +description: 介绍如何在本地环境中从源代码编译和运行 GreptimeDB,包括系统要求和依赖项。 +--- + # 立即开始 本页面介绍如何在本地环境中从源代码运行 GreptimeDB。 @@ -6,7 +11,7 @@ ### 系统和架构 -目前,GreptimeDB 仅支持 Linux(amd64)和 macOS(amd64 和 Apple Silicone)。 +目前,GreptimeDB 支持 Linux(amd64 和 arm64)、macOS(amd64 和 Apple Silicone)和 Windows。 ### 构建依赖项 @@ -17,6 +22,7 @@ - Protobuf([指南][2]) - 编译 proto 文件 - 请注意,版本需要 >= 3.15。你可以使用 `protoc --version` 检查它。 +- 机器:建议内存在16GB以上 或者 使用[mold](https://github.com/rui314/mold)工具以降低链接时的内存使用。 [1]: [2]: @@ -43,10 +49,20 @@ cargo build # --release ## 单元测试 -GreptimeDB 经过了充分的测试,整个单元测试套件都随源代码一起提供。通过以下命令来运行测试: +GreptimeDB 经过了充分的测试,整个单元测试套件都随源代码一起提供。要测试它们,请使用 [nextest](https://nexte.st/index.html)。 + +要使用 cargo 安装 nextest,请运行: + +```shell +cargo install cargo-nextest --locked +``` + +或者,你可以查看他们的[文档](https://nexte.st/docs/installation/pre-built-binaries/)以了解其他安装方式。 + +安装好 nextest 后,你可以使用以下命令运行测试套件: ```shell -cargo test --workspace +cargo nextest run ``` ## Docker diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/contributor-guide/how-to/how-to-trace-greptimedb.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/how-to/how-to-trace-greptimedb.md similarity index 94% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7/contributor-guide/how-to/how-to-trace-greptimedb.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/how-to/how-to-trace-greptimedb.md index 5ba8572a3..6c1d922ac 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/contributor-guide/how-to/how-to-trace-greptimedb.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/how-to/how-to-trace-greptimedb.md @@ -1,3 +1,8 @@ +--- +keywords: [tracing, 分布式追踪, tracing 上下文, RPC 调用, 代码埋点] +description: 介绍如何在 GreptimeDB 中使用 Rust 的 tracing 框架进行代码埋点,包括在 RPC 中定义和传递 tracing 上下文的方法。 +--- + # How to trace GreptimeDB GreptimeDB 使用 Rust 的 [tracing](https://docs.rs/tracing/latest/tracing/) 框架进行代码埋点,tracing 的具体原理和使用方法参见 tracing 的官方文档。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/contributor-guide/how-to/how-to-use-tokio-console.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/how-to/how-to-use-tokio-console.md similarity index 82% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7/contributor-guide/how-to/how-to-use-tokio-console.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/how-to/how-to-use-tokio-console.md index 8c78f2937..605035d57 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/contributor-guide/how-to/how-to-use-tokio-console.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/how-to/how-to-use-tokio-console.md @@ -1,3 +1,8 @@ +--- +keywords: [tokio-console, GreptimeDB, 构建配置, 启动配置, 调试工具] +description: 介绍如何在 GreptimeDB 中启用 tokio-console,包括构建和启动时的配置方法。 +--- + # 如何在 GreptimeDB 中启用 tokio-console 本文介绍了如何在 GreptimeDB 中启用 [tokio-console](https://github.com/tokio-rs/console)。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/contributor-guide/how-to/how-to-write-sdk.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/how-to/how-to-write-sdk.md similarity index 91% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7/contributor-guide/how-to/how-to-write-sdk.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/how-to/how-to-write-sdk.md index c0c57d547..ce9c84873 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/contributor-guide/how-to/how-to-write-sdk.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/how-to/how-to-write-sdk.md @@ -1,3 +1,8 @@ +--- +keywords: [gRPC SDK, GreptimeDatabase, GreptimeRequest, GreptimeResponse, 插入请求] +description: 介绍如何为 GreptimeDB 开发一个 gRPC SDK,包括 GreptimeDatabase 服务的定义、GreptimeRequest 和 GreptimeResponse 的结构。 +--- + # 如何为 GreptimeDB 开发一个 gRPC SDK GreptimeDB 的 gRPC SDK 只需要处理写请求即可。读请求是标准 SQL 或 PromQL ,可以由任何 JDBC 客户端或 Prometheus diff --git a/versioned_docs/version-0.7/contributor-guide/metasrv/admin-api.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/metasrv/admin-api.md similarity index 61% rename from versioned_docs/version-0.7/contributor-guide/metasrv/admin-api.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/metasrv/admin-api.md index 912611c55..2afc712ec 100644 --- a/versioned_docs/version-0.7/contributor-guide/metasrv/admin-api.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/metasrv/admin-api.md @@ -1,92 +1,97 @@ +--- +keywords: [Admin API, 健康检查, leader 查询, 心跳检测, 维护模式] +description: 介绍 Metasrv 的 Admin API,包括健康检查、leader 查询和心跳检测等功能。 +--- + # Admin API -The Admin API provides a simple way to view cluster information, including metasrv health detection, metasrv leader query, database metadata query, and datanode heartbeat detection. +Admin 提供了一种简单的方法来查看集群信息,包括 metasrv 健康检测、metasrv leader 查询、数据库元数据查询和数据节点心跳检测。 -The Admin API is an HTTP service that provides a set of RESTful APIs that can be called through HTTP requests. The Admin API is simple, user-friendly and safe. -Available APIs: +Admin API 是一个 HTTP 服务,提供一组可以通过 HTTP 请求调用的 RESTful API。Admin API 简单、用户友好且安全。 +可用的 API: - /health - /leader - /heartbeat - /maintenance -All these APIs are under the parent resource `/admin`. +所有这些 API 都在父资源 `/admin` 下。 -In the following sections, we assume that your metasrv instance is running on localhost port 3002. +在以下部分中,我们假设你的 metasrv 实例运行在本地主机的 3002 端口。 -## /health HTTP endpoint +## /health HTTP 端点 -The `/health` endpoint accepts GET HTTP requests and you can use this endpoint to check the health of your metasrv instance. +`/health` 端点接受 GET HTTP 请求,你可以使用此端点检查你的 metasrv 实例的健康状况。 -### Definition +### 定义 ```bash curl -X GET http://localhost:3002/admin/health ``` -### Examples +### 示例 -#### Request +#### 请求 ```bash curl -X GET http://localhost:3002/admin/health ``` -#### Response +#### 响应 ```json OK ``` -## /leader HTTP endpoint +## /leader HTTP 端点 -The `/leader` endpoint accepts GET HTTP requests and you can use this endpoint to query the leader's addr of your metasrv instance. +`/leader` 端点接受 GET HTTP 请求,你可以使用此端点查询你的 metasrv 实例的 leader 地址。 -### Definition +### 定义 ```bash curl -X GET http://localhost:3002/admin/leader ``` -### Examples +### 示例 -#### Request +#### 请求 ```bash curl -X GET http://localhost:3002/admin/leader ``` -#### Response +#### 响应 ```json 127.0.0.1:3002 ``` -## /heartbeat HTTP endpoint +## /heartbeat HTTP 端点 -The `/heartbeat` endpoint accepts GET HTTP requests and you can use this endpoint to query the heartbeat of all datanodes. +`/heartbeat` 端点接受 GET HTTP 请求,你可以使用此端点查询所有数据节点的心跳。 -You can also query the heartbeat data of the datanode for a specified `addr`, however, specifying `addr` in the path is optional. +你还可以查询指定 `addr` 的数据节点的心跳数据,但在路径中指定 `addr` 是可选的。 -### Definition +### 定义 ```bash curl -X GET http://localhost:3002/admin/heartbeat ``` -| Query String Parameter | Type | Optional/Required | Definition | -|:-----------------------|:-------|:------------------|:--------------------------| -| addr | String | Optional | The addr of the datanode. | +| 查询字符串参数 | 类型 | 可选/必选 | 定义 | +|:---------------|:-------|:----------|:--------------------| +| addr | String | 可选 | 数据节点的地址。 | -### Examples +### 示例 -#### Request +#### 请求 ```bash curl -X GET 'http://localhost:3002/admin/heartbeat?addr=127.0.0.1:4100' ``` -#### Response +#### 响应 ```json [ @@ -244,25 +249,25 @@ curl -X GET 'http://localhost:3002/admin/heartbeat?addr=127.0.0.1:4100' ] ``` -## /maintenance HTTP endpoint +## /maintenance HTTP 端点 -The metasrv will ignore detected region failures when under maintenance. This is useful when the datanodes are planned to be unavailable for a short period of time; for example, rolling upgrade for datanodes. +当处于维护状态时,metasrv 将忽略检测到的区域故障。这在数据节点计划短时间不可用时非常有用,例如数据节点的滚动升级时。 ### GET -The `/maintenance` endpoint accepts GET HTTP requests and you can use this endpoint to query the maintenance status of your metasrv instance. +`/maintenance` 端点接受 GET HTTP 请求,你可以使用此端点查询你的 metasrv 实例的维护状态。 ```bash curl -X GET http://localhost:3002/admin/maintenance ``` -#### Request +#### 请求 ```bash curl -X GET http://localhost:3002/admin/maintenance ``` -#### Response +#### 响应 ```text Maintenance mode is disabled @@ -270,23 +275,23 @@ Maintenance mode is disabled ### PUT -The `/maintenance` endpoint accepts PUT HTTP requests and you can toggle the maintenance status of your metasrv instance. +`/maintenance` 端点接受 PUT HTTP 请求,你可以切换你的 metasrv 实例的维护状态。 ```bash curl -X PUT http://localhost:3002/admin/maintenance ``` -| Query String Parameter | Type | Optional/Required | Definition | -|:-----------------------|:-------|:------------------|:--------------------------| -| enable | String | Required | 'true' or 'false' | +| 查询字符串参数 | 类型 | 可选/必选 | 定义 | +|:---------------|:-------|:----------|:--------------------| +| enable | String | 必选 | 'true' 或 'false' | -#### Request +#### 请求 ```bash curl -X PUT http://localhost:3002/admin/maintenance?enable=true ``` -#### Response +#### 响应 ```text Maintenance mode enabled diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/metasrv/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/metasrv/overview.md new file mode 100644 index 000000000..6cc821b0f --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/metasrv/overview.md @@ -0,0 +1,162 @@ +--- +keywords: [Metasrv, 元数据存储, 请求路由, 负载均衡, 高可用性] +description: 介绍 Metasrv 的功能、架构和与前端的交互方式。 +--- + +# 概述 + +![meta](/meta.png) + +## Metasrv 包含什么 + +- 存储元数据(Catalog, Schema, Table, Region 等) +- 请求路由器。它告诉前端在哪里写入和读取数据。 +- 数据节点的负载均衡,决定谁应该处理新的表创建请求,更准确地说,它做出资源分配决策。 +- 选举与高可用性,GreptimeDB 设计为 Leader-Follower 架构,只有 leader 节点可以写入,而 follower 节点可以读取,follower 节点的数量通常 >= 1,当 leader 不可用时,follower 节点需要能够快速切换为 leader。 +- 统计数据收集(通过每个节点上的心跳报告),如 CPU、负载、节点上的表数量、平均/峰值数据读写大小等,可用作分布式调度的基础。 + +## 前端如何与 Metasrv 交互 + +首先,请求路由器中的路由表结构如下(注意这只是逻辑结构,实际存储结构可能不同,例如端点可能有字典压缩)。 + +```txt + table_A + table_name + table_schema // 用于物理计划 + regions + region_1 + mutate_endpoint + select_endpoint_1, select_endpoint_2 + region_2 + mutate_endpoint + select_endpoint_1, select_endpoint_2, select_endpoint_3 + region_xxx + table_B + ... +``` + +### 创建表 + +1. 前端发送 `CREATE TABLE` 请求到 Metasrv。 +2. 根据请求中包含的分区规则规划 Region 数量。 +3. 检查数据节点可用资源的全局视图(通过心跳收集)并为每个 Region 分配一个节点。 +4. 前端创建表并在成功创建后将 `Schema` 存储到 Metasrv。 + +### `Insert` + +1. 前端从 Metasrv 获取指定表的路由。注意,最小的路由单元是表的路由(多个 Region),即包含该表所有 Region 的地址。 +2. 最佳实践是前端首先从本地缓存中获取路由并将请求转发到数据节点。如果路由不再有效,则数据节点有义务返回 `Invalid Route` 错误,前端重新从 Metasrv 获取最新数据并更新其缓存。路由信息不经常变化,因此,前端使用惰性策略维护缓存是足够的。 +3. 前端处理可能包含多个表和多个 Region 的一批写入,因此前端需要根据“路由表”拆分用户请求。 + +### `Select` + +1. 与 `Insert` 类似,前端首先从本地缓存中获取路由表。 +2. 与 `Insert` 不同,对于 `Select`,前端需要从路由表中提取只读节点(follower),然后根据优先级将请求分发到 leader 或 follower 节点。 +3. 前端的分布式查询引擎根据路由信息分发多个子查询任务并聚合查询结果。 + +## Metasrv 架构 + +![metasrv-architecture](/metasrv-architecture.png) + +## 分布式共识 + +如你所见,Metasrv 依赖于分布式共识,因为: + +1. 首先,Metasrv 必须选举一个 leader ,数据节点只向 leader 发送心跳,我们只使用单个 Metasrv 节点接收心跳,这使得基于全局信息进行一些计算或调度变得容易且快速。至于数据节点如何连接到 leader ,这由 MetaClient 决定(使用重定向,心跳请求变为 gRPC 流,使用重定向比转发更不容易出错),这对数据节点是透明的。 +2. 其次,Metasrv 必须为数据节点提供选举 API,以选举“写入”和“只读”节点,并帮助数据节点实现高可用性。 +3. 最后,`Metadata`、`Schema` 和其他数据必须在 Metasrv 上可靠且一致地存储。因此,基于共识的算法是存储它们的理想方法。 + +对于 Metasrv 的第一个版本,我们选择 Etcd 作为共识算法组件(Metasrv 设计时考虑适应不同的实现,甚至创建一个新的轮子),原因如下: + +1. Etcd 提供了我们需要的 API,例如 `Watch`、`Election`、`KV` 等。 +2. 我们只执行两个分布式共识任务:选举(使用 `Watch` 机制)和存储(少量元数据),这两者都不需要我们定制自己的状态机,也不需要基于 raft 定制自己的状态机;少量数据也不需要多 raft 组支持。 +3. Metasrv 的初始版本使用 Etcd,使我们能够专注于 Metasrv 的功能,而不需要在分布式共识算法上花费太多精力,这提高了系统设计(避免与共识算法耦合)并有助于初期的快速开发,同时通过良好的架构设计,未来可以轻松接入优秀的共识算法实现。 + +## 心跳管理 + +数据节点与 Metasrv 之间的主要通信方式是心跳请求/响应流,我们希望这是唯一的通信方式。这个想法受到 [TiKV PD](https://github.com/tikv/pd) 设计的启发,我们在 [RheaKV](https://github.com/sofastack/sofa-jraft/tree/master/jraft-rheakv/rheakv-pd) 中有实际经验。请求发送其状态,而 Metasrv 通过心跳响应发送不同的调度指令。 + +心跳可能携带以下数据,但这不是最终设计,我们仍在讨论和探索究竟应该收集哪些数据。 + +``` +service Heartbeat { + // 心跳,心跳可能有很多内容,例如: + // 1. 要注册到 Metasrv 并可被其他节点发现的元数据。 + // 2. 一些性能指标,例如负载、CPU 使用率等。 + // 3. 正在执行的计算任务数量。 + rpc Heartbeat(stream HeartbeatRequest) returns (stream HeartbeatResponse) {} +} + +message HeartbeatRequest { + RequestHeader header = 1; + + // 自身节点 + Peer peer = 2; + // leader 节点 + bool is_leader = 3; + // 实际报告时间间隔 + TimeInterval report_interval = 4; + // 节点状态 + NodeStat node_stat = 5; + // 此节点中的 Region 状态 + repeated RegionStat region_stats = 6; + // follower 节点和状态,在 follower 节点上为空 + repeated ReplicaStat replica_stats = 7; +} + +message NodeStat { + // 此期间的读取容量单位 + uint64 rcus = 1; + // 此期间的写入容量单位 + uint64 wcus = 2; + // 此节点中的表数量 + uint64 table_num = 3; + // 此节点中的 Region 数量 + uint64 region_num = 4; + + double cpu_usage = 5; + double load = 6; + // 节点中的读取磁盘 I/O + double read_io_rate = 7; + // 节点中的写入磁盘 I/O + double write_io_rate = 8; + + // 其他 + map attrs = 100; +} + +message RegionStat { + uint64 region_id = 1; + TableName table_name = 2; + // 此期间的读取容量单位 + uint64 rcus = 3; + // 此期间的写入容量单位 + uint64 wcus = 4; + // 近似 Region 大小 + uint64 approximate_size = 5; + // 近似行数 + uint64 approximate_rows = 6; + + // 其他 + map attrs = 100; +} + +message ReplicaStat { + Peer peer = 1; + bool in_sync = 2; + bool is_learner = 3; +} +``` + +## Central Nervous System (CNS) + +我们要构建一个算法系统,该系统依赖于每个节点的实时和历史心跳数据,应该做出一些更智能的调度决策并将其发送到 Metasrv 的 Autoadmin 单元,该单元分发调度决策,由数据节点本身或更可能由 PaaS 平台执行。 + +## 工作负载抽象 + +工作负载抽象的级别决定了 Metasrv 生成的调度策略(如资源分配)的效率和质量。 + +DynamoDB 定义了 RCUs 和 WCUs(读取容量单位/写入容量单位),解释说 RCU 是一个 4KB 数据的读取请求,WCU 是一个 1KB 数据的写入请求。当使用 RCU 和 WCU 描述工作负载时,更容易实现性能可测量性并获得更有信息量的资源预分配,因为我们可以将不同的硬件能力抽象为 RCU 和 WCU 的组合。 + +然而,GreptimeDB 面临比 DynamoDB 更复杂的情况,特别是 RCU 不适合描述需要大量计算的 GreptimeDB 读取工作负载。我们正在努力解决这个问题。 + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/metasrv/selector.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/metasrv/selector.md new file mode 100644 index 000000000..13aac3ad9 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/metasrv/selector.md @@ -0,0 +1,47 @@ +--- +keywords: [Selector, Metasrv, Datanode, 路由表, 负载均衡] +description: 介绍 Metasrv 中的 Selector,包括其类型和配置方法。 +--- + +# Selector + +## 介绍 + +什么是 `Selector`?顾名思义,它允许用户从给定的 `namespace` 和 `context` 中选择 `Item`s。有一个相关的 `trait`,也叫做 `Selector`,其定义可以在[这里][0]找到。 + +[0]: https://github.com/GreptimeTeam/greptimedb/blob/main/src/meta-srv/src/selector.rs + +在 `Metasrv` 中存在一个特定的场景。当 `Frontend` 向 `Metasrv` 发送建表请求时,`Metasrv` 会创建一个路由表(表的创建细节不在这里赘述)。在创建路由表时,`Metasrv` 需要选择适当的 `Datanode`s,这时候就需要用到 `Selector`。 + +## Selector 类型 + +`Metasrv` 目前提供以下几种类型的 `Selectors`: + +### LeasebasedSelector + +`LeasebasedSelector` 从所有可用的(也就是在租约期间内)`Datanode` 中随机选择,其特点是简单和快速。 + +### LoadBasedSelector + +`LoadBasedSelector` 按照负载来选择,负载值则由每个 `Datanode` 上的 region 数量决定,较少的 region 表示较低的负载,`LoadBasedSelector` 优先选择低负载的 `Datanode`。 + +### RoundRobinSelector [默认选项] +`RoundRobinSelector` 以轮询的方式选择 `Datanode`。在大多数情况下,这是默认的且推荐的选项。如果你不确定选择哪个,通常它就是正确的选择。 + +## 配置 + +您可以在启动 `Metasrv` 服务时通过名称配置 `Selector`。 + +- LeasebasedSelector: `lease_based` 或 `LeaseBased` +- LoadBasedSelector: `load_based` 或 `LoadBased` +- RoundRobinSelector: `round_robin` 或 `RoundRobin` + +例如: + +```shell +cargo run -- metasrv start --selector round_robin +``` + +```shell +cargo run -- metasrv start --selector RoundRobin +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/contributor-guide/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/overview.md similarity index 94% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7/contributor-guide/overview.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/overview.md index cdcee36b2..b8a457cbc 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/contributor-guide/overview.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/overview.md @@ -1,3 +1,8 @@ +--- +keywords: [架构, 关键概念, 数据处理, 组件交互, 数据库] +description: 介绍 GreptimeDB 的架构、关键概念和工作原理,包括各组件的交互方式和数据处理流程。 +--- + # 概述 ## 架构 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/tests/integration-test.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/tests/integration-test.md new file mode 100644 index 000000000..63ffa56bc --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/tests/integration-test.md @@ -0,0 +1,14 @@ +--- +keywords: [集成测试, Rust, HTTP, gRPC, 测试工具] +description: 介绍 GreptimeDB 的集成测试,包括测试范围和如何运行这些测试。 +--- + +# 集成测试 + +## 介绍 + +集成测试使用 Rust 测试工具(`#[test]`)编写,与单元测试不同,它们被单独放置在 +[这里](https://github.com/GreptimeTeam/greptimedb/tree/main/tests-integration)。 +它涵盖了涉及多个组件的场景,其中一个典型案例是与 HTTP/gRPC 相关的功能。你可以查看 +其[文档](https://github.com/GreptimeTeam/greptimedb/blob/main/tests-integration/README.md)以获取更多信息。 + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/tests/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/tests/overview.md new file mode 100644 index 000000000..1366187cb --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/tests/overview.md @@ -0,0 +1,6 @@ +# 测试 + +## 介绍 + +我们的团队进行了大量测试,以确保 GreptimeDB 的行为。本章将介绍几种用于测试 GreptimeDB 的重要方法,以及如何使用它们。 + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/tests/sqlness-test.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/tests/sqlness-test.md new file mode 100644 index 000000000..a1683dbda --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/tests/sqlness-test.md @@ -0,0 +1,50 @@ +--- +keywords: [Sqlness 测试, SQL, 测试套件, 测试文件, 测试案例] +description: 介绍 GreptimeDB 的 Sqlness 测试,包括测试文件类型、组织测试案例和运行测试的方法。 +--- + +# Sqlness 测试 + +## 介绍 + +SQL 是 `GreptimeDB` 的一个重要用户接口。我们为它提供了一个单独的测试套件(名为 `sqlness`)。 + +## Sqlness 手册 + +### 测试文件 + +Sqlness 有三种类型的文件 + +- `.sql`:测试输入,仅包含 SQL +- `.result`:预期的测试输出,包含 SQL 和其结果 +- `.output`:不同的输出,包含 SQL 和其结果 + +`.result` 和 `.output` 都是输出(执行结果)文件。区别在于 `.result` 是标准(预期)输出,而 `.output` 是错误输出。因此,如果生成了 `.output` 文件,意味着测试结果不同,测试失败。你应该检查变更日志来解决问题。 + +你只需要在 `.sql` 文件中编写测试 SQL,然后运行测试。第一次运行时会生成 `.output` 文件,因为没有 `.result` 文件进行比较。如果你确认 `.output` 文件中的内容是正确的,可以将其重命名为 `.result`,这意味着它是预期输出。 + +任何时候都应该只有两种文件类型,`.sql` 和 `.result` —— 否则,存在 `.output` 文件意味着测试失败。这就是为什么我们不应该在 `.gitignore` 中忽略 `.output` 文件类型,而是跟踪它并确保它不存在。 + +### 组织测试案例 + +输入案例的根目录是 `tests/cases`。它包含几个子目录,代表不同的测试模式。例如,`standalone/` 包含所有在 `greptimedb standalone start` 模式下运行的测试。 + +在第一级子目录下(例如 `cases/standalone`),你可以随意组织你的测试案例。Sqlness 会递归地遍历每个文件并运行它们。 + +## 运行测试 + +与其他测试不同,这个测试工具是以二进制目标形式存在的。你可以用以下命令运行它 + +```shell +cargo run --bin sqlness-runner +``` + +它会自动完成以下步骤:编译 `GreptimeDB`,启动它,抓取测试并将其发送到服务器,然后收集和比较结果。你只需要检查是否有新的 `.output` 文件。如果没有,恭喜你,测试通过了 🥳! + +### 运行特定测试 + +```shell +cargo sqlness -t your_test +``` + +如果你指定了第二个参数,则只会执行名称中包含指定字符串的测试案例。Sqlness 还支持基于环境的过滤。过滤器接受正则表达式字符串,并会检查格式为 `env:case` 的案例名称。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/tests/unit-test.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/tests/unit-test.md new file mode 100644 index 000000000..79c73775b --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/contributor-guide/tests/unit-test.md @@ -0,0 +1,28 @@ +--- +keywords: [单元测试, Rust, nextest, 测试覆盖率, CI] +description: 介绍 GreptimeDB 的单元测试,包括如何编写、运行和检查测试覆盖率。 +--- + +# 单元测试 + +## 介绍 + +单元测试嵌入在代码库中,通常放置在被测试逻辑的旁边。它们使用 Rust 的 `#[test]` 属性编写,并可以使用 `cargo nextest run` 运行。 + +GreptimeDB 代码库不支持默认的 `cargo` 测试运行器。推荐使用 [`nextest`](https://nexte.st/)。你可以通过以下命令安装它: + +```shell +cargo install cargo-nextest --locked +``` + +然后运行测试(这里 `--workspace` 不是必须的) + +```shell +cargo nextest run +``` + +注意,如果你的 Rust 是通过 `rustup` 安装的,请确保使用 `cargo` 安装 `nextest`,而不是像 `homebrew` 这样的包管理器,否则会弄乱你的本地环境。 + +## 覆盖率 + +我们的持续集成(CI)作业有一个“覆盖率检查”步骤。它会报告有多少代码被单元测试覆盖。请在你的补丁中添加必要的单元测试。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/db-cloud-shared/migrate/_migrate-from-prometheus.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/db-cloud-shared/migrate/_migrate-from-prometheus.md new file mode 100644 index 000000000..bd989340b --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/db-cloud-shared/migrate/_migrate-from-prometheus.md @@ -0,0 +1,30 @@ +GreptimeDB 可以用来存储 [Prometheus](https://prometheus.io/) 的时间序列数据。 +此外,GreptimeDB 通过其 HTTP API 支持 Prometheus 查询语言。 +这可以使你轻松将 Prometheus 的 long-term storage 切换到 GreptimeDB。 + +## 数据模型的区别 + +要了解 Prometheus 和 GreptimeDB 数据模型之间的差异,请参阅 Ingest Data 文档中的[数据模型](/user-guide/ingest-data/for-observerbility/prometheus.md#data-model)部分。 + +## Prometheus Remote Write + + + +## Prometheus HTTP API 与 PromQL + +GreptimeDB 通过其 HTTP API 支持 Prometheus 查询语言 (PromQL)。 + + +## 使用 Grafana 可视化数据 + +对于习惯使用 Grafana 可视化 Prometheus 数据的开发人员,你可以继续使用相同的 Grafana 仪表板来可视化存储在 GreptimeDB 中的数据。 + + +## 参考阅读 + +请参考以下博客文章查看 GreptimeDB 与 Prometheus 的集成教程及用户故事: + +- [如何配置 GreptimeDB 作为 Prometheus 的长期存储](https://greptime.com/blogs/2024-08-09-prometheus-backend-tutorial) +- [Scale Prometheus: K8s 部署 GreptimeDB 集群作为 Prometheus 长期存储](https://greptime.com/blogs/2024-10-07-scale-prometheus) +- [「用户故事」从 Thanos 到 GreptimeDB,我们实现了 Prometheus 高效长期存储](https://greptime.com/blogs/2024-10-16-thanos-migration-to-greptimedb) + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/db-cloud-shared/migrate/migrate-from-influxdb.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/db-cloud-shared/migrate/migrate-from-influxdb.md new file mode 100644 index 000000000..cd7a3a5e3 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/db-cloud-shared/migrate/migrate-from-influxdb.md @@ -0,0 +1,257 @@ +本文档将帮助你了解 GreptimeDB 和 InfluxDB 的数据模型之间的区别,并指导你完成迁移过程。 + +## 数据模型的区别 + +要了解 InfluxDB 和 GreptimeDB 的数据模型之间的差异,请参考写入数据文档中的[数据模型](/user-guide/ingest-data/for-iot/influxdb-line-protocol.md#数据模型)。 + +## 数据库连接信息 + +在写入或查询数据之前,需要了解 InfluxDB 和 GreptimeDB 之间的数据库连接信息的差异。 + +- **Token**:InfluxDB API 中的 token 用于身份验证,与 GreptimeDB 身份验证相同。 + 当使用 InfluxDB 的客户端库或 HTTP API 与 GreptimeDB 交互时,你可以使用 `` 作为 token。 +- **Organization**:GreptimeDB 中没有组织。 +- **Bucket**:在 InfluxDB 中,bucket 是时间序列数据的容器,与 GreptimeDB 中的数据库名称相同。 + + + +## 写入数据 + +GreptimeDB 兼容 InfluxDB 的行协议格式,包括 v1 和 v2。 +这意味着你可以轻松地从 InfluxDB 迁移到 GreptimeDB。 + +### HTTP API + +你可以使用以下 HTTP API 请求将 measurement 写入 GreptimeDB: + + + +### Telegraf + +GreptimeDB 支持 InfluxDB 行协议也意味着 GreptimeDB 与 Telegraf 兼容。 +要配置 Telegraf,只需将 GreptimeDB 的 URL 添加到 Telegraf 配置中: + + + +### 客户端库 + +使用 InfluxDB 客户端库写入数据到 GreptimeDB 非常直接且简单。 +你只需在客户端配置中包含 URL 和身份验证信息。 + +例如: + + + +除了上述语言之外,GreptimeDB 还支持其他 InfluxDB 支持的客户端库。 +你可以通过参考上面提供的连接信息代码片段,使用你喜欢的语言编写代码。 + +## 查询数据 + +GreptimeDB 不支持 Flux 和 InfluxQL,而是使用 SQL 和 PromQL。 + +SQL 是一种通用的用于管理和操作关系数据库的语言。 +具有灵活的数据检索、操作和分析功能, +减少了已经熟悉 SQL 的用户的学习曲线。 + +PromQL(Prometheus 查询语言)允许用户实时选择和聚合时间序列数据, +表达式的结果可以显示为图形,也可以在 Prometheus 的表达式浏览器中以表格数据的形式查看, +或通过 [HTTP API](/user-guide/query-data/promql.md#prometheus-http-api) 传递给外部系统。 + +假设你要查询过去 24 小时内记录的 `monitor` 表中的最大 CPU。 +在 InfluxQL 中,查询如下: + +```sql [InfluxQL] +SELECT + MAX("cpu") +FROM + "monitor" +WHERE + time > now() - 24h +GROUP BY + time(1h) +``` + +此 InfluxQL 查询计算 `monitor` 表中 `cpu`字段的最大值, +其中时间大于当前时间减去 24 小时,结果以一小时为间隔进行分组。 + +该查询在 Flux 中的表达如下: + +```flux [Flux] +from(bucket: "public") + |> range(start: -24h) + |> filter(fn: (r) => r._measurement == "monitor") + |> aggregateWindow(every: 1h, fn: max) +``` + +在 GreptimeDB SQL 中,类似的查询为: + +```sql [SQL] +SELECT + ts, + host, + AVG(cpu) RANGE '1h' as mean_cpu +FROM + monitor +WHERE + ts > NOW() - INTERVAL '24 hours' +ALIGN '1h' TO NOW +ORDER BY ts DESC; +``` + +在该 SQL 查询中, +`RANGE` 子句确定了 AVG(cpu) 聚合函数的时间窗口, +而 `ALIGN` 子句设置了时间序列数据的对齐时间。 +有关按时间窗口分组的更多详细信息,请参考[按时间窗口聚合数据](/user-guide/query-data/sql.md#按时间窗口聚合数据)文档。 + +在 PromQL 中,类似的查询为: + +```promql +avg_over_time(monitor[1h]) +``` + +要查询最后 24 小时的时间序列数据, +你需要执行此 PromQL 并使用 HTTP API 的 `start` 和 `end` 参数定义时间范围。 +有关 PromQL 的更多信息,请参考 [PromQL](https://prometheus.io/docs/prometheus/latest/querying/basics/) 文档。 + +## 可视化数据 + + + +## 迁移数据 + +你可以通过以下步骤实现从 InfluxDB 到 GreptimeDB 的数据无缝迁移: + +![Double write to GreptimeDB and InfluxDB](/migrate-influxdb-to-greptimedb.drawio.svg) + +1. 同时将数据写入 GreptimeDB 和 InfluxDB,以避免迁移过程中的数据丢失。 +2. 从 InfluxDB 导出所有历史数据,并将数据导入 GreptimeDB。 +3. 停止向 InfluxDB 写入数据,并移除 InfluxDB 服务器。 + +### 双写 GreptimeDB 和 InfluxDB + +将数据双写 GreptimeDB 和 InfluxDB 是迁移过程中防止数据丢失的有效策略。 +当使用 InfluxDB 的[客户端库](#client-libraries)时,你可以建立两个客户端实例,一个用于 GreptimeDB,另一个用于 InfluxDB。 +有关如何使用 InfluxDB 行协议将数据写入 GreptimeDB 的操作,请参考[写入数据](#write-data)部分。 + +如果无需保留所有历史数据, +你可以双写一段时间以积累所需的最新数据, +然后停止向 InfluxDB 写入数据并仅使用 GreptimeDB。 +如果需要完整迁移所有历史数据,请按照接下来的步骤操作。 + +### 从 InfluxDB v1 服务器导出数据 + +创建一个临时目录来存储 InfluxDB 的导出数据。 + +```shell +mkdir -p /path/to/export +``` + +使用 InfluxDB 的 [`influx_inspect export` 命令](https://docs.influxdata.com/influxdb/v1/tools/influx_inspect/#export) 导出数据。 + +```shell +influx_inspect export \ + -database \ + -end \ + -lponly \ + -datadir /var/lib/influxdb/data \ + -waldir /var/lib/influxdb/wal \ + -out /path/to/export/data +``` + +- `-database` 指定要导出的数据库。 +- `-end` 指定要导出的数据的结束时间。 +必须是[RFC3339 格式](https://datatracker.ietf.org/doc/html/rfc3339),例如 `2024-01-01T00:00:00Z`。 +你可以使用同时写入 GreptimeDB 和 InfluxDB 时的时间戳作为结束时间。 +- `-lponly` 指定只导出行协议数据。 +- `-datadir` 指定数据目录的路径,请见[InfluxDB 数据设置](https://docs.influxdata.com/influxdb/v1/administration/config/#data-settings)中的配置。 +- `-waldir` 指定 WAL 目录的路径,请见[InfluxDB 数据设置](https://docs.influxdata.com/influxdb/v1/administration/config/#data-settings)中的配置。 +- `-out` 指定输出目录。 + +导出的 InfluxDB 行协议数据类似如下: + +```txt +disk,device=disk1s5s1,fstype=apfs,host=bogon,mode=ro,path=/ inodes_used=356810i 1714363350000000000 +diskio,host=bogon,name=disk0 iops_in_progress=0i 1714363350000000000 +disk,device=disk1s6,fstype=apfs,host=bogon,mode=rw,path=/System/Volumes/Update inodes_used_percent=0.0002391237988702021 1714363350000000000 +... +``` + +### 从 InfluxDB v2 服务器导出数据 + +创建一个临时目录来存储 InfluxDB 的导出数据。 + +```shell +mkdir -p /path/to/export +``` + +使用 InfluxDB 的 [`influx inspect export-lp` 命令](https://docs.influxdata.com/influxdb/v2/reference/cli/influxd/inspect/export-lp/) 导出数据。 + +```shell +influxd inspect export-lp \ + --bucket-id \ + --engine-path /var/lib/influxdb2/engine/ \ + --end \ + --output-path /path/to/export/data +``` + +- `--bucket-id` 指定要导出的 bucket ID。 +- `--engine-path` 指定引擎目录的路径,请见[InfluxDB 数据设置](https://docs.influxdata.com/influxdb/v2.0/reference/config-options/#engine-path)中的配置。 +- `--end` 指定要导出的数据的结束时间。 +必须是[RFC3339 格式](https://datatracker.ietf.org/doc/html/rfc3339),例如 `2024-01-01T00:00:00Z`。 +你可以使用同时写入 GreptimeDB 和 InfluxDB 时的时间戳作为结束时间。 +- `--output-path` 指定输出目录。 + +命令行的执行结果类似如下: + +```json +{"level":"info","ts":1714377321.4795408,"caller":"export_lp/export_lp.go:219","msg":"exporting TSM files","tsm_dir":"/var/lib/influxdb2/engine/data/307013e61d514f3c","file_count":1} +{"level":"info","ts":1714377321.4940555,"caller":"export_lp/export_lp.go:315","msg":"exporting WAL files","wal_dir":"/var/lib/influxdb2/engine/wal/307013e61d514f3c","file_count":1} +{"level":"info","ts":1714377321.4941633,"caller":"export_lp/export_lp.go:204","msg":"export complete"} +``` + +导出的 InfluxDB 行协议数据类似如下: + +```txt +cpu,cpu=cpu-total,host=bogon usage_idle=80.4448912910468 1714376180000000000 +cpu,cpu=cpu-total,host=bogon usage_idle=78.50167052182304 1714376190000000000 +cpu,cpu=cpu-total,host=bogon usage_iowait=0 1714375700000000000 +cpu,cpu=cpu-total,host=bogon usage_iowait=0 1714375710000000000 +... +``` + +### 导入数据到 GreptimeDB + +在将数据导入 GreptimeDB 之前,如果数据文件过大,建议将数据文件拆分为多个片段: + +```shell +split -l 100000 -d -a 10 data data. +# -l [line_count] 创建长度为 line_count 行的拆分文件。 +# -d 使用数字后缀而不是字母后缀。 +# -a [suffix_length] 使用 suffix_length 个字母来形成文件名的后缀。 +``` + +你可以使用 HTTP API 导入数据,如[写入数据](#写入数据)部分所述。 +下方提供的脚本将帮助你从文件中读取数据并将其导入 GreptimeDB。 + +假设你的当前位置是存储数据文件的目录: + +```shell +. +├── data.0000000000 +├── data.0000000001 +├── data.0000000002 +... +``` + +将 GreptimeDB 的连接信息设置到环境变量中: + +```shell +export GREPTIME_USERNAME= +export GREPTIME_PASSWORD= +export GREPTIME_HOST= +export GREPTIME_DB= +``` + +将数据导入到 GreptimeDB: + + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/db-cloud-shared/tutorials/monitor-host-metrics/go-demo.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/db-cloud-shared/tutorials/monitor-host-metrics/go-demo.md similarity index 92% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7/db-cloud-shared/tutorials/monitor-host-metrics/go-demo.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/db-cloud-shared/tutorials/monitor-host-metrics/go-demo.md index 903f8e252..eef904911 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/db-cloud-shared/tutorials/monitor-host-metrics/go-demo.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/db-cloud-shared/tutorials/monitor-host-metrics/go-demo.md @@ -11,7 +11,7 @@ go get go.opentelemetry.io/otel@v1.16.0 \ ``` 安装所需的包后,在 `app.go` 中编写代码创建一个 metric exporter 对象,将 metrics 发送到 GreptimeDB。 -请参考 [GreptimeDB](/user-guide/clients/otlp.md) 或 [GreptimeCloud](/greptimecloud/integrations/otlp.md) 中的 OTLP 集成文档获取 exporter 的相关配置。 +请参考 [GreptimeDB](/user-guide/protocols/opentelemetry.md) 或 [GreptimeCloud](/greptimecloud/integrations/otlp.md) 中的 OTLP 集成文档获取 exporter 的相关配置。 ```go auth := base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", *username, *password))) diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/db-cloud-shared/tutorials/monitor-host-metrics/influxdb-demo.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/db-cloud-shared/tutorials/monitor-host-metrics/influxdb-demo.md similarity index 89% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7/db-cloud-shared/tutorials/monitor-host-metrics/influxdb-demo.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/db-cloud-shared/tutorials/monitor-host-metrics/influxdb-demo.md index 08344f978..aaada18b8 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/db-cloud-shared/tutorials/monitor-host-metrics/influxdb-demo.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/db-cloud-shared/tutorials/monitor-host-metrics/influxdb-demo.md @@ -52,6 +52,6 @@ do done ``` -请参阅 [GreptimeDB](/user-guide/clients/influxdb-line.md) 或 [GreptimeCloud](/greptimecloud/integrations/influxdb.md) 中的 InfluxDB 文档以获取 InfluxDB API 中的 `host`、`database`、`username` 和 `password` 信息, +请参阅 [GreptimeDB](/user-guide/protocols/influxdb-line-protocol.md) 或 [GreptimeCloud](/greptimecloud/integrations/influxdb.md) 中的 InfluxDB 文档以获取 InfluxDB API 中的 `host`、`database`、`username` 和 `password` 信息, 恭喜你完成了 Demo 的核心部分!现在可以按照 [GitHub 库](https://github.com/GreptimeCloudStarters/quick-start-influxdb-line-protocol)中 `README.md` 文件中的说明运行完整的 Demo。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/db-cloud-shared/tutorials/monitor-host-metrics/java-demo.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/db-cloud-shared/tutorials/monitor-host-metrics/java-demo.md similarity index 94% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7/db-cloud-shared/tutorials/monitor-host-metrics/java-demo.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/db-cloud-shared/tutorials/monitor-host-metrics/java-demo.md index 356ddceac..16cbce108 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/db-cloud-shared/tutorials/monitor-host-metrics/java-demo.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/db-cloud-shared/tutorials/monitor-host-metrics/java-demo.md @@ -22,7 +22,7 @@ dependencies { ``` 安装完依赖后,编写代码创建一个 Metric Exporter 对象,用于将 metrics 发送到 GreptimeDB。 -请参考 [GreptimeDB](/user-guide/clients/otlp.md) 或 [GreptimeCloud](/greptimecloud/integrations/otlp.md) 中的 OTLP 集成文档获取 exporter 的相关配置。 +请参考 [GreptimeDB](/user-guide/protocols/opentelemetry.md) 或 [GreptimeCloud](/greptimecloud/integrations/otlp.md) 中的 OTLP 集成文档获取 exporter 的相关配置。 ```java String endpoint = String.format("https://%s/v1/otlp/v1/metrics", dbHost); diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/db-cloud-shared/tutorials/monitor-host-metrics/mysql-demo.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/db-cloud-shared/tutorials/monitor-host-metrics/mysql-demo.md similarity index 91% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7/db-cloud-shared/tutorials/monitor-host-metrics/mysql-demo.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/db-cloud-shared/tutorials/monitor-host-metrics/mysql-demo.md index e0902c3ed..574b4741a 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/db-cloud-shared/tutorials/monitor-host-metrics/mysql-demo.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/db-cloud-shared/tutorials/monitor-host-metrics/mysql-demo.md @@ -62,6 +62,6 @@ do done ``` -请参阅 [GreptimeDB](/user-guide/clients/mysql.md) 或 [GreptimeCloud](/greptimecloud/integrations/mysql.md) 中的 MySQL 文档以获取命令中的 `host`、`database`、`username` 和 `password` 信息, +请参阅 [GreptimeDB](/user-guide/protocols/mysql.md) 或 [GreptimeCloud](/greptimecloud/integrations/mysql.md) 中的 MySQL 文档以获取命令中的 `host`、`database`、`username` 和 `password` 信息, 恭喜你完成了 Demo 的核心部分!现在可以按照 [GitHub 库](https://github.com/GreptimeCloudStarters/quick-start-mysql)中 `README.md` 文件中的说明运行完整的 Demo。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/db-cloud-shared/tutorials/monitor-host-metrics/node-js-demo.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/db-cloud-shared/tutorials/monitor-host-metrics/node-js-demo.md similarity index 91% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7/db-cloud-shared/tutorials/monitor-host-metrics/node-js-demo.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/db-cloud-shared/tutorials/monitor-host-metrics/node-js-demo.md index c20fc265e..ee6005e24 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/db-cloud-shared/tutorials/monitor-host-metrics/node-js-demo.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/db-cloud-shared/tutorials/monitor-host-metrics/node-js-demo.md @@ -25,7 +25,7 @@ npm install @opentelemetry/api@1.4.1 \ ``` 成功安装依赖后,创建一个名为 `app.ts` 的文件,并编写代码创建一个 metric exporter 对象,将 metrics 发送到 GreptimeDB。 -请参考 [GreptimeDB](/user-guide/clients/otlp.md) 或 [GreptimeCloud](/greptimecloud/integrations/otlp.md) 中的 OTLP 集成文档获取 exporter 的相关配置。 +请参考 [GreptimeDB](/user-guide/protocols/opentelemetry.md) 或 [GreptimeCloud](/greptimecloud/integrations/otlp.md) 中的 OTLP 集成文档获取 exporter 的相关配置。 ```ts const exporter = new OTLPMetricExporter({ diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/db-cloud-shared/tutorials/monitor-host-metrics/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/db-cloud-shared/tutorials/monitor-host-metrics/overview.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7/db-cloud-shared/tutorials/monitor-host-metrics/overview.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/db-cloud-shared/tutorials/monitor-host-metrics/overview.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/db-cloud-shared/tutorials/monitor-host-metrics/prometheus-demo.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/db-cloud-shared/tutorials/monitor-host-metrics/prometheus-demo.md similarity index 87% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7/db-cloud-shared/tutorials/monitor-host-metrics/prometheus-demo.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/db-cloud-shared/tutorials/monitor-host-metrics/prometheus-demo.md index 411819cd4..f31ac919e 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/db-cloud-shared/tutorials/monitor-host-metrics/prometheus-demo.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/db-cloud-shared/tutorials/monitor-host-metrics/prometheus-demo.md @@ -11,7 +11,7 @@ ```yaml services: prometheus: - image: prom/prometheus:latest + image: prom/prometheus:VAR::prometheusVersion container_name: prometheus depends_on: - node_exporter @@ -21,7 +21,7 @@ services: - ./prometheus-greptimedb.yml:/etc/prometheus/prometheus.yml:ro node_exporter: - image: quay.io/prometheus/node-exporter:latest + image: quay.io/prometheus/node-exporter:VAR::nodeExporterVersion container_name: node_exporter ports: - 9100:9100 @@ -53,7 +53,7 @@ remote_write: password: ``` -通过上面的配置文件,Prometheus 从 node exporter 中抓取指标并将其发送到 GreptimeDB。有关 ``, ``, `` 和 `` 的信息,请参考 [GreptimeDB](/user-guide/clients/prometheus.md) 或 [GreptimeCloud](/greptimecloud/integrations/prometheus/quick-setup.md) 中的 Prometheus 文档。 +通过上面的配置文件,Prometheus 从 node exporter 中抓取指标并将其发送到 GreptimeDB。有关 ``, ``, `` 和 `` 的信息,请参考 [GreptimeDB](/user-guide/integrations/prometheus.md) 或 [GreptimeCloud](/greptimecloud/integrations/prometheus.md) 中的 Prometheus 文档。 最后启动 Docker 容器: diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/db-cloud-shared/tutorials/monitor-host-metrics/python-demo.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/db-cloud-shared/tutorials/monitor-host-metrics/python-demo.md similarity index 93% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7/db-cloud-shared/tutorials/monitor-host-metrics/python-demo.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/db-cloud-shared/tutorials/monitor-host-metrics/python-demo.md index 4b46e93c9..1a0ba4b44 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/db-cloud-shared/tutorials/monitor-host-metrics/python-demo.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/db-cloud-shared/tutorials/monitor-host-metrics/python-demo.md @@ -25,7 +25,7 @@ pip install -r requirements.txt ``` 安装所需的包后,创建名为 `main.py` 的新文件并编写代码创建一个 metric exporter 对象,将 metrics 发送到 GreptimeDB。 -请参考 [GreptimeDB](/user-guide/clients/otlp.md) 或 [GreptimeCloud](/greptimecloud/integrations/otlp.md) 中的 OTLP 集成文档获取 exporter 的相关配置。 +请参考 [GreptimeDB](/user-guide/protocols/opentelemetry.md) 或 [GreptimeCloud](/greptimecloud/integrations/otlp.md) 中的 OTLP 集成文档获取 exporter 的相关配置。 ```python from opentelemetry import metrics diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/enterprise/administration/disaster-recovery/dr-solution-based-on-active-active-failover.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/enterprise/administration/disaster-recovery/dr-solution-based-on-active-active-failover.md new file mode 100644 index 000000000..6bfc5183c --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/enterprise/administration/disaster-recovery/dr-solution-based-on-active-active-failover.md @@ -0,0 +1,69 @@ +--- +keywords: [双活互备, 灾难恢复, RPO, RTO, 故障转移, 读写模式] +description: 介绍 GreptimeDB 中基于双活互备的灾难恢复解决方案,包括不同读写模式的 RPO 和 RTO 目标,以及故障转移的处理方法。 +--- + +# 基于双活互备的 DR 解决方案 + +## RPO + +在 GreptimeDB 的“双活互备”架构中,有两个节点,分别独立部署了 GreptimeDB 服务。这两个节点都可以提供客户端执行读写的能力。然而,为了达到 +RTO 和 RPO 的目标,我们需要对两节点进行一些配置。首先我们介绍一下在“双活互备”架构中读写的模式。 + +对于读操作: + +- `SingleRead`:读操作只在一个节点上执行,结果直接返回给客户端。 +- `DualRead`:读操作在两个节点上都执行,结果将会合并去重后返回给客户端。 + +下图展示了这两种读操作模式的区别: + +![disaster-recovery-read-mode](/disaster-recovery-read-mode.png) + +对于写操作: + +- `SyncWrite`:写操作在两个节点上都执行,只有在两个节点都写成功后才会返回给客户端(成功)。 +- `AsyncWrite`:写操作仍然在两个节点上执行,但是在发起节点写成功后就会返回给客户端。另一个节点会异步地从发起节点接收写操作的复制。 + +下图展示了这两种写操作模式的区别: + +![disaster-recovery-write-mode](/disaster-recovery-write-mode.png) + +所以读写操作有四种组合,它们的 RPO 如下: + +| RPO | `SingleRead` | `DualRead` | +|--------------|--------------|------------| +| `SyncWrite` | 0 | 0 | +| `AsyncWrite` | 两节点之间的网络延迟 | 0 | + +在 `SyncWrite` 模式下,由于两个节点之间的写操作是同步的,所以 RPO 总是 0,无论读操作是什么模式。然而,`SyncWrite` +要求两个节点同时正常运行以处理写操作。如果你的工作负载是读多写少,并且可以容忍一段系统不可用的时间来恢复两个节点的健康状态,我们建议使用 `SyncWrite + SingleRead` +组合。 + +另一个可以达到 0 RPO 的组合是 `AsyncWrite + DualRead`。这是上面所说的相反情况,适用于写多读少的工作负载,两节点可用性的限制要求可以降低。 + +最后一个组合是 `AsyncWrite + SingleRead`。这是对两节点可用性最宽松的要求。如果两个节点之间的网络状况良好,并且节点可以被可靠地托管,例如,两个节点托管在一个 +AZ(可用区,或“数据中心”)内的虚拟机系统中,你可能更倾向这种组合。当然,只要记住 RPO 不是 0。 + +## RTO + +为了保持我们的双活互备架构的最低需求,我们没有要求第三个节点或第三个服务来处理 GreptimeDB 的故障转移。一般来说,有几种方法可以处理故障转移: + +- 通过一个 LoadBalancer。如果你可以额外腾出另一个节点来部署一个 LoadBalancer + 如 [Nginx](https://docs.nginx.com/nginx/admin-guide/load-balancer/tcp-udp-load-balancer/),或者你有其他 LoadBalance + 服务,我们推荐这种方式。 + DR-LoadBalancer +- 通过客户端 SDK 的故障转移机制。例如,如果你使用 MySQL Connector/j,你可以通过在连接 URL + 中设置多个主机和端口来配置故障转移(参见其[文档](https://dev.mysql.com/doc/connector-j/en/connector-j-config-failover.html) + )。PostgreSQL 的驱动程序[也有相同的机制](https://jdbc.postgresql.org/documentation/use/#connection-fail-over) + 。这是处理故障转移最简单的方法,但并不是每个客户端 SDK 都支持这种故障转移机制。 + DR-SDK +- 内部的 endpoint 更新机制。如果你可以检测到节点的故障,那么就可以在你的代码中更新 GreptimeDB 的 endpoint。 + +:::tip NOTE +请参考 "[解决方案比较](/user-guide/administration/disaster-recovery/overview.md#解决方案比较)" 来比较不同灾难恢复解决方案的 RPO 和 RTO。 +::: + +## 总结 + +在 GreptimeDB 的“双活互备”架构中,你可以选择不同的读写模式组合来实现你的 RPO 目标。至于 RTO,我们依赖外部机制来处理故障转移。一个 +LoadBalancer 是最适合的。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/enterprise/administration/disaster-recovery/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/enterprise/administration/disaster-recovery/overview.md new file mode 100644 index 000000000..c56a3d165 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/enterprise/administration/disaster-recovery/overview.md @@ -0,0 +1,12 @@ +--- +keywords: [灾难恢复, DR 解决方案, 双活互备, 数据库, 恢复方案] +description: 概述 GreptimeDB Enterprise 中的灾难恢复解决方案,特别是基于双活互备的 DR 解决方案,并提供相关链接以获取更多信息。 +--- + +# 概述 + +作为分布式数据库,GreptimeDB 提供了不同的灾难恢复(DR)解决方案。 + +请参考 GreptimeDB OSS 文档中的[灾难恢复概述](/user-guide/administration/disaster-recovery/overview.md)了解 Greptime 提供的所有灾难恢复解决方案。本章节仅介绍在 GreptimeDB Enterprise 中提供的解决方案。 + +- [基于双活互备的 DR 解决方案](./dr-solution-based-on-active-active-failover.md) diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/enterprise/autopilot/region-balancer.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/enterprise/autopilot/region-balancer.md new file mode 100644 index 000000000..fc997d232 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/enterprise/autopilot/region-balancer.md @@ -0,0 +1,39 @@ +--- +keywords: [Region Balancer, Datanode, 负载均衡, 窗口大小, 负载阈值, 迁移] +description: 介绍 Region Balancer 插件,通过配置窗口大小和负载阈值来均衡 Datanode 上的 Region 写入负载,避免频繁迁移。 +--- + +# Region Balancer + +该插件用于均衡 Datanode 上的 Region 写入负载,通过指定的窗口大小和负载阈值来避免频繁的 Region 迁移。 + +```toml +[[plugins]] +[plugins.region_balancer] + +window_size = "45s" + +window_stability_threshold = 2 + +min_load_threshold = "10MB" + +tick_interval = "45s" +``` + +## 配置项说明 + +- `window_size`: string + - **说明**: 滑动窗口的时间跨度,用于计算区域负载的短期平均值。窗口期内的负载变化会被平滑,减轻短期突增对负载均衡的影响。 + - **单位**: 时间(支持格式:`"45s"` 表示 45 秒)。 + - **建议**: 根据集群负载波动情况配置,较大的窗口会使负载均衡响应更平稳。 +- `window_stability_threshold`: integer + - **说明**: 连续多少个窗口必须满足触发条件后,才会进行迁移操作。该阈值用于防止频繁的平衡操作,只在持续不均衡的情况下进行 Region 迁移。 + - **建议**: 较大的值会延迟再平衡的触发,适用于负载波动较大的系统;值为 2 表示需要至少两个连续窗口符合条件。 +- `min_load_threshold`: string + - **说明**: 触发 Region 迁移的最小写负载阈值(每秒字节数)。当节点的负载低于该值时,将不会触发迁移。 + - **单位**: 字节(例如,`"10MB"` 表示 10 MiB)。 + - **建议**: 设置为合理的最小值,防止小负载情况触发迁移。值可以根据系统实际流量进行调整。 +- `tick_interval`: string + - **说明**: 平衡器的运行间隔时间,控制负载均衡任务的触发频率。 + - **单位**: 时间(例如,"45s" 表示 45 秒)。 + - **建议**: 根据系统的响应速度和负载变化频率设置。较短的间隔可以更快响应负载变化,但可能增加系统开销。 \ No newline at end of file diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/enterprise/deployments/audit-logging.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/enterprise/deployments/audit-logging.md new file mode 100644 index 000000000..11365559e --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/enterprise/deployments/audit-logging.md @@ -0,0 +1,81 @@ +--- +keywords: [审计日志, 配置方法, 监控数据库操作, 合规性, JSON 格式] +description: 介绍 GreptimeDB 中的审计日志功能,包括审计日志的格式、配置方法及注意事项,帮助用户监控数据库操作并确保合规性。 +--- + +# 审计日志 + +数据库的审计日志记录了对数据库执行的操作。审计日志有助于监控用户活动,检测可疑操作,并确保组织内外的合规性。本文档提供了 +GreptimeDB 中审计日志的概述以及如何配置它。 + +## 概述 + +一条在 GreptimeDB 上执行的语句(SQL 或 PromQL)会被记录在审计日志中(当然,前提是已经将其配置为需要被审计)。以下是审计日志中的一条示例记录: + +```json +{ + "time": "2024-11-05T06:13:19.903713Z", + "user": "greptime_user", + "source": "Mysql", + "class": "Ddl", + "command": "Create", + "object_type": "Database", + "object_names": [ + "audit_test" + ], + "statement": "CREATE DATABASE audit_test" +} +``` + +正如您所见,一条审计日志的记录被格式化为 JSON 字符串。它包含以下字段: + +- `time`: 语句执行的时间。格式为带有 UTC 时区的 ISO 8601 日期和时间的字符串。 +- `user`: 发送该请求的用户。 +- `source`: 请求的来源,也即用于连接到 GreptimeDB 的协议。 +- `class`: 语句的类别,如 "Read"、"Write" 或 "DDL" 等。 +- `command`: 语句的命令,如 "Select"、"Insert" 或 "Create" 等。 +- `object_type`: 语句操作的对象的类型,如 "Database"、"Table" 或 "Flow" 等。 +- `object_names`: 语句操作的对象的名称。 +- `statement`: 语句本身。 + +## 配置 + +审计日志作为 GreptimeDB 的插件提供。要启用并配置它,请将以下 TOML 添加到 GreptimeDB 配置文件中: + +```toml +[[plugins]] +# 将审计日志插件添加到 GreptimeDB 中。 +[plugins.audit_log] +# 是否启用审计日志,默认为 true。 +enable = true +# 存储审计日志文件的目录。默认为 "/tmp" 中的一个目录。 +dir = "/tmp/greptimedb/logs/" +# 允许审计的语句的来源。此选项作为过滤器:如果语句不来自这些配置的来源之一,则不会记录在审计日志中。 +# 多个来源用逗号(",")分隔。 +# 所有可配置的来源是 "Http"、"Mysql" 和 "Postgres"。 +# 一个特殊的 "all"(默认值)表示所有来源。 +sources = "all" +# 允许审计的语句的类别。此选项作为过滤器:如果语句的类别不匹配这些配置的值之一,则不会记录在审计日志中。 +# 多个类别用逗号(",")分隔。 +# 所有可配置的类别是 "Read"、"Write"、"Admin"、"DDL" 和 "Misc"。 +# 一个特殊的 "all" 表示所有类别。默认值为 "DDL" 和 "Admin"。 +classes = "ddl,admin" +# 允许审计的语句的命令。此选项作为过滤器:如果语句的命令不匹配这些配置的值之一,则不会记录在审计日志中。 +# 多个命令用逗号(",")分隔。 +# 所有可配置的命令是 "Promql"、"Select"、"Copy"、"Insert"、"Delete"、"Create"、"Alter"、"Truncate"、"Drop"、"Admin" 和 "Misc"。 +# 一个特殊的 "all"(默认值)表示所有命令。 +commands = "all" +# 允许审计的对象类型。此选项作为过滤器:如果语句的目标对象不匹配这些配置的值之一,则不会记录在审计日志中。 +# 多个对象类型用逗号(",")分隔。 +# 所有可配置的对象类型是 "Database"、"Table"、"View"、"Flow"、"Index" 和 "Misc"。 +# 一个特殊的 "all"(默认值)表示所有对象类型。 +object_types = "all" +# 保留的审计日志文件的最大数量。默认为 30。 +# 审计日志每天生成一个新的。 +max_log_files = 30 +``` + +## 注意 + +如果没有正确配置的话,审计日志可能会非常庞大。例如,在业务繁忙的 GreptimeDB 中,将 "`all`" 设置给所有的 `sources`,`classes`, +`commands` 和 `object_types` 会记录在 GreptimeDB 上执行的所有语句,导致一个非常大的审计日志文件。这可能会轻易地耗尽磁盘空间。因此,强烈建议合理地配置审计日志插件以避免这种情况。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/enterprise/deployments/authentication.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/enterprise/deployments/authentication.md new file mode 100644 index 000000000..7f71e90e8 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/enterprise/deployments/authentication.md @@ -0,0 +1,83 @@ +--- +keywords: [LDAP 鉴权, simple bind, search bind, 配置示例, 身份验证] +description: 介绍 GreptimeDB Enterprise 中的 LDAP 鉴权功能,包括 simple bind 和 search bind 两种模式的配置示例及使用方法。 +--- + +# LDAP 鉴权 + +除了 GreptimeDB OSS 中内置的 [Static User Provider](/user-guide/deployments/authentication/static.md), +GreptimeDB Enterprise 还提供了连接到外部 LDAP 服务器进行身份验证的功能。 + +## 配置 + +与 [PostgreSQL 中的 LDAP 机制相似](https://www.postgresql.org/docs/current/auth-ldap.html), 在 GreptimeDB 中,LDAP 鉴权也分为两种模式:"simple bind" 和 "search bind"。 + +在 "simple bind" 模式下,GreptimeDB 会构造一个格式为 `{prefix}{username}{suffix}` 的 "DN"(distinguished name) +,并使用客户端传来的密码向 LDAP 服务发起”绑定 (bind)“。绑定的结果就是鉴权的结果。一个典型配置是,`prefix` 参数指定 `cn=`, +`suffix` 用于指定 DN 的其余部分。`username` 将会被替换为客户端发来的用户名。 + +以下一个 LDAP user provider "simple bind" 模式的配置文件示例: + +```toml +# LDAP 服务地址。 +server = "127.0.0.1" +# LDAP 服务端口。 +port = 636 +# 设置为 "ldap" 以使用 LDAP scheme,"ldaps" 以使用 LDAPS。 +# GreptimeDB 和 LDAP 服务之间的连接一开始时是未加密的。连接建立后升级到 TLS。这是 LDAPv3 的 "StartTLS" 标准。 +scheme = "ldaps" + +# LDAP 鉴权模式。`bind = "simple"` 和 `bind = "search"` 只能选择其一。 +[auth_mode] +# 以下配置仅在 simple bind 模式下使用: +bind = "simple" +# 当进行 simple bind 鉴权时,用于构造绑定 DN 的前缀。 +prefix = "cn=" +# 当进行 simple bind 鉴权时,用于构造绑定 DN 的后缀。 +suffix = ",dc=example,dc=com" +``` + +在 "search bind" 模式中,GreptimeDB 首先会使用配置文件中设置的固定用户名和密码(`bind_dn` 和 `bind_passwd`)尝试绑定到 LDAP +目录。然后 GreptimeDB 会在 LDAP 目录中搜索尝试登录到数据库的用户。搜索将在 `base_dn` 下的子树中进行,由 `search_filter` +过滤,并尝试对 `search_attribute` 中指定的属性进行精确匹配。一旦在搜索中找到用户,GreptimeDB +会以此用户重新绑定到目录,使用客户端指定的密码,以验证登录是否正确。这种方法允许用户对象在 LDAP 目录中的位置更加灵活,但会导致向 +LDAP 服务器发出两个额外的请求。 + +以下 toml 片段展示了 GreptimeDB LDAP user provider "search bind" 模式的配置文件示例。在上面的 "simple bind" 模式配置文件中显示的 +`server`、`port` 和 `scheme` 的公共部分被省略了: + +```toml +[auth_mode] +# 以下配置仅在 search bind 模式下使用: +bind = "search" +# 进行 search bind 鉴权时,开始搜索用户的根 DN。 +base_dn = "ou=people,dc=example,dc=com" +# 进行 search bind 鉴权时,首先进行绑定的用户 DN。 +bind_dn = "cn=admin,dc=example,dc=com" +# 进行 search bind 鉴权时,首先进行绑定的用户密码。 +bind_passwd = "secret" +# 进行 search bind 鉴权时,用于匹配的用户属性。 +# 如果未指定属性,则将使用 uid 属性。 +search_attribute = "cn" +# 进行 search bind 鉴权时,使用的搜索过滤器。 +# "$username" 将被替换为客户端传来的用户名。 +# 这允许比 search_attribute 更灵活的用户搜索。 +search_filter = "(cn=$username)" +``` + +## 在 GreptimeDB 中使用 LDAP User Provider + +要使用 LDAP User Provider,首先参照上文配置你的 LDAP 鉴权模式,然后在启动 GreptimeDB 时使用 `--user-provider` 参数,将其设置为 +`ldap_user_provider:`。例如,如果你有一个配置文件是 `/home/greptimedb/ldap.toml`,你可以使用以下命令启动一个 +standalone GreptimeDB: + +```shell +greptime standalone start --user-provider=ldap_user_provider:/home/greptimedb/ldap.toml +``` + +现在你就可以使用你的 LDAP 用户账户创建一个连接到 GreptimeDB 了。 + +:::tip 注意 +如果你使用 MySQL CLI 连接到配置了 LDAP User Provider 的 GreptimeDB,你需要在 MySQL CLI 中指定 +`--enable-cleartext-plugin`。 +::: diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/enterprise/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/enterprise/overview.md new file mode 100644 index 000000000..0ce59f653 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/enterprise/overview.md @@ -0,0 +1,30 @@ +--- +keywords: [企业版, 时序数据库, BYOC, 全托管云, 边云一体] +description: GreptimeDB Enterprise 是为企业设计的时序数据库解决方案,提供了 BYOC、全托管云、边云一体等部署方式,并包含高级功能如双活互备的 DR 解决方案、LDAP 身份验证和审计日志。 +--- + +# 概述 + +GreptimeDB Enterprise 是专为满足企业特定需求而设计的强大时序数据库解决方案。 +除了开源版 GreptimeDB 中提供的所有功能外, +Enterprise 版还提供更多增强功能,帮助企业优化数据效率并显著降低成本,使企业能够使用时序数据做出更智能、更快速的决策。 + +解决方案包括: + +- **将数据库部署在你的云中 - Bring Your Own Cloud(BYOC**: 利用你自己的云基础设施来托管 GreptimeDB,提供广泛的定制和灵活性以满足你的业务需求。此服务包括对你的云资源的全面管理和强大的安全措施,以保护你的基础设施。 +- **全托管的独立云**: Greptime 团队提供完全托管的专用云环境,确保最佳性能、增强的安全性和卓越的可靠性,以满足你的企业需求。 +- **[边云一体解决方案](https://greptime.com/product/carcloud)**: 用于管理从边缘设备到云的时序数据,实现整个基础设施的实时分析和洞察的全面解决方案。 +- 针对物联网 (IoT)、可观测等行业的特定解决方案。 + +本章节概述了 GreptimeDB Enterprise 中可用的高级功能。有关获取试用或购买,请[联系我们](https://greptime.cn/contactus)。 + +## 功能 + +- [基于双活互备的 DR 解决方案](./administration/disaster-recovery/overview.md):通过高级灾难恢复解决方案确保服务不中断和数据保护。 +- [LDAP 身份验证](./deployments/authentication.md):使用基于 LDAP 的身份验证进行访问管理,确保系统安全。 +- [审计日志](./deployments/audit-logging.md): 用详细的审计日志追踪并记录用户的行为。 +- 更多功能文档即将推出! + +## 发布说明 + +- [24.11](./release-notes/release-24_11.md) diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/enterprise/release-notes/release-24_11.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/enterprise/release-notes/release-24_11.md new file mode 100644 index 000000000..0f4e58777 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/enterprise/release-notes/release-24_11.md @@ -0,0 +1,55 @@ +--- +keywords: [Region Rebalance, 管理控制台, LDAP User Provider, 审计日志, 开源版改进] +description: GreptimeDB 企业版 24.11 版本介绍了 Region Rebalance、管理控制台、LDAP User Provider、审计日志等新特性,并基于开源版 v0.10 引入了多项改进。 +--- + +# Release 24.11 + +我们很高兴向大家介绍 GreptimeDB 企业版的 24.11 版本。 + +## 特性亮点 + +### Region Rebalance + +为了增强 GreptimeDB 的弹性,Region Rebalance 功能允许在数据节点之间灵活地重新分配 +Region,无论是否由手动或动态触发。 + +这一前瞻性的措施带来了多个关键优势,包括均衡工作负载、优化资源利用,并确保在计划 +维护期间无缝运行。 + +### GreptimeDB 企业版管理控制台 + +我们带来了首个版本的 GreptimeDB 企业版管理控制台的用户界面。 + +此版本提供了一系列功能,包括: + +- 慢查询分析与调试 +- 详细的集群拓扑信息 +- 实时查看集群指标和日志 + +### LDAP User Provider + +将您自己的 LDAP 用户数据库与 GreptimeDB 企业版进行连接。我们实现了灵活的配置选项 +支持,无论是简单的还是复杂的认证机制。 + +### 审计日志 + +提供日志以跟踪数据库中的查询操作,并记录以下信息: + +- 查询类型:读取、写入、DDL 或其他 +- 命令:SELECT、INSERT 等 +- 对象类型:操作的目标对象,例如表、数据库等 + +### GreptimeDB 开源版特性 + +本版本基于 GreptimeDB 开源版 v0.10。开源基础引入了一些新功能: + +- 向量数据类型支持用于相似性搜索 +- 二级索引更新:用户现在可以在任何列上创建二级索引 +- 添加了表选项以更新 TTL、压缩参数和全文索引设置 +- JSON 数据类型和函数的支持 +- Loki Remote Write 的早期支持 +- 更多地理空间的通用函数(UDF)包括空间关系与测量、S2索引等。 + +请参阅[这里](https://docs.greptime.com/release-notes/release-0-10-0)以获取完整的 +变更日志。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/faq-and-others/faq.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/faq-and-others/faq.md new file mode 100644 index 000000000..de3d5e00a --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/faq-and-others/faq.md @@ -0,0 +1,214 @@ +# 常见问题 + +### What would be the use cases for a time-series database? + +Common use cases for time-series database include but are not limited to the following four scenarios: + +1. Monitor applications and infrastructure +2. Store and access IoT data +3. Process self-driving vehicle data +4. Understand financial trends + +### TSDB features that you concern + +Please refer to [features that you concern](/user-guide/concepts/features-that-you-concern.md). + + +### How is the performance of GreptimeDB when used for non-time-series DB tables? + +GreptimeDB supports SQL and can deal with non-time-series data, especially efficient for high concurrent and throughput data writing. However, we develop GreptimeDB for a specific domain (time-series scenarios), and it doesn't support transactions and can't delete data efficiently. + +### Does GreptimeDB have a Go driver? + +Yes, you can find our Go SDK here: https://github.com/GreptimeTeam/greptimedb-ingester-go. + +Currently, we support MySQL protocol, you can check it out on the [user guide](/user-guide/protocols/mysql.md). + +HTTP API is also available, please see [this article](/user-guide/protocols/http.md) for more information. + +### Can GreptimeDB be used as a Rust alternative to Prometheus in the observable area? + +GreptimeDB has initially implemented native support for PromQL, with compatibility in GreptimeDB v0.7 surpassing 80%, making it comparable to VictoriaMetrics. + +### Is GreptimeDB compatible with Grafana? + +Yes, It's compatible with Grafana. + +GreptimeDB has an official Grafana plugin: [greptimedb-grafana-datasource](https://github.com/GreptimeTeam/greptimedb-grafana-datasource/) + +GreptimeDB also supports MySQL and PostgreSQL protocol, so you can use [MySQL or PG grafana +plugin](https://grafana.com/docs/grafana/latest/datasources/mysql/) to config GreptimeDB as a datasource. Then you can use SQL to query the data. + +Also, we are implementing PromQL natively which is frequently used with Grafana. + +### How does this compare to Loki? Is there a crate with Rust bindings available, preferably as tracing or logging subscriber? + +GreptimeDB has primarily focused on metrics, but will soon offer log storage and full-text search capabilities for logs. These features are expected to be available in version 0.9, which is anticipated to be released in early July. + +### When will GreptimeDB release its first GA version? + +The current version has not yet reached General Availability version standards. In line with our Greptime 2024 Roadmap, we plan to achieve a production-level version with the update to v1.0 in August. More details: https://github.com/GreptimeTeam/greptimedb/issues/3412. + +### Are there any plans/works done for the official UI for GreptimeDB so that it would be possible to check cluster status, list of tables, statistics etc? + +Yes, we open sourced the dashboard for users to query and visualize their data. +Please check out our initial version on [GitHub Repo](https://github.com/GreptimeTeam/dashboard). + +### Does GreptimeDB support schemaless? + +Yes, GreptimeDB is a schemaless database without need for creating tables in advance. The table and columns will be created automatically when writing data with protocol gRPC, InfluxDB, OpentsDB, Prometheus remote write. + +For more information, refer to [this document](/user-guide/administration/manage-data/basic-table-operations.md#create-table). + +### How do you measure the passing rate of PromQL compatibility tests? Is there any testing framework? + +There’s [an issue](https://github.com/GreptimeTeam/greptimedb/issues/1042) to track the PromQL compatibility tests passing rate. It's based on Prometheus's compliance test. + +### Where’s the name “Greptime” coming from? + +Because `grep` is the most useful command line tool on \*nix platform to search data, and time means time series. So Greptime is to help everybody to search/find value in time series data. + +### Is there any good first issue that can help beginners get started quickly? + +Yes, beginners can filter issues with ["good first issue"](https://github.com/GreptimeTeam/greptimedb/issues?q=label%3A%22good+first+issue%22) label. Additionally, more good first issues will be released on a rolling basis, so stay tuned! + +### Does GreptimeDB support dumping table-level data to S3? + +You can use the [`COPY TO` command](/reference/sql/copy.md#s3) to dump table-level data to S3. + +### Can [Nightingale](https://n9e.github.io) now be directly integrated with GreptimeDB? How is its compatibility? + +Currently, GreptimeDB's compatibility efforts are primarily focused on the implementation of native PromQL. Going forward, we will continue to enhance compatibility with MetricQL's extended syntax. + +### If I delete the database, can I use the `DROP DATABASE` command? + +Yes, the `DROP DATABASE` command has been implemented in version 0.8. You can refer to the official documentation for usage: [`Drop Database`](https://docs.greptime.com/reference/sql/drop#drop). + +### Are there any retention policy? + +We have implemented table level Time-To-Live (TTL) in [this PR](https://github.com/GreptimeTeam/greptimedb/pull/1052). You can refer to the TTL option of the table build statement [here](/user-guide/concepts/features-that-you-concern.md#can-i-set-ttl-or-retention-policy-for-different-tables-or-measurements). + +And since 0.8, GreptimeDB already supports database level `TTL` too, read the [CREATE DATABASE](/reference/sql/create.md#create-database). + +### What are the main differences between Greptime and another time-series database built on DataFusion like InfluxDB? + +At GreptimeDB, we share some technical similarities with InfluxDB, both using Datafusion, Arrow, Parquet, and built on object storage. However, we differ in several key aspects: + +- Open-Source Strategy: Unlike InfluxDB, which only open-sources its standalone version, our entire distributed cluster version is open-source. Our architecture can even run on edge Android systems. +- Distributed Architecture: Our architecture is more aligned with HBase's Region/RegionServer design. Our Write-Ahead Log (WAL) uses Kafka, and we're exploring a quorum-based implementation in the future. +- Workload and Services: We focus on a hybrid workload combining time series and analytics. This integration aims to enhance resource efficiency and real-time performance for users. We also offer [GreptimeCloud](https://greptime.com/product/cloud), a commercial cloud service. +- Storage Engine Design: Our pluggable storage engine is versatile. For scenarios with many small data tables, like in Prometheus, we have a dedicated Metrics storage engine. +- Query Language Support: We support PromQL for observability and SQL for data analysis, and incorporate Python for complex data processing. InfluxDB, on the other hand, uses InfluxQL and SQL. + +We're a young, rapidly evolving project and always looking to improve. For more details, visit [our Blog](https://greptime.com/blogs/) and [Contributor Guide](https://docs.greptime.com/contributor-guide/overview). We welcome your interest and contributions! + +### As a first-timer looking to contribute to GreptimeDB, where can I find a comprehensive guide to get started? + +Welcome! Please refer to our [contribution guide](https://github.com/GreptimeTeam/greptimedb/blob/main/CONTRIBUTING.md). For those new to GreptimeDB, we have a selected collection of [good first issues](https://github.com/GreptimeTeam/greptimedb/issues?q=is%3Aopen+is%3Aissue+label%3A%22Good+first+issue%22). Feel free to reach us in Slack channel anytime! + +### Can GreptimeDB be used for a large-scale internal metrics collection system similar to Fb's Gorilla or Google's Monarch, with a preference for in-memory data and high availability? Are there plans for asynchronous WAL or optional disk storage, and how is data replication handled without WAL? + +GreptimeDB supports asynchronous WAL and is developing a per-table WAL toggle for more control. A tiered storage approach, starting with in-memory caching, is also in development. For data replication, data flushed to remote stores like S3 is replicated independently of WAL. The details for tiered storage are tracked in issue [db#2516](https://github.com/GreptimeTeam/greptimedb/issues/2516). A remote WAL implementation based on Apache Kafka ensures the durability of unflushed data in cluster mode. + +### Does GreptimeDB have a way to handle absolute counters that can reset, like InfluxDB's non-negative differential? How do aggregations work with these counters, and is PromQL preferred over SQL for them? Also, is there a plan to integrate PromQL functions into SQL, similar to InfluxDB v3? + +GreptimeDB, like Prometheus, handles counters effectively. Functions like` reset()`, `rate()`, or `delta()` in GreptimeDB are designed to automatically detect and adjust for counter resets. While it's not recommended to use the `deriv()` function on a counter since it's meant for gauges, you can apply `rate()` to your counter and then use `deriv()`. PromQL is indeed more suitable for operations involving counters, given its origin in Prometheus. However, we are exploring the integration of PromQL functions into SQL for greater flexibility. If you're interested in implementing functions into GreptimeDB, we have documentation available which you can check out: [Greptime Documentation](https://github.com/GreptimeTeam/greptimedb/blob/main/docs/how-to/how-to-write-aggregate-function.md). + +### What are the feature differences between the open-source version and the cloud version of GreptimeDB? + +Thank you for asking, here are some key points: + +- **Foundational Features**: The foundational features, including the ingestion protocol, SQL capabilities, and storage functions, are largely identical between the two versions. However, GreptimeCloud offers advanced SQL functions and additional features. +- **Fully Managed Service**: GreptimeCloud is a fully managed service that supports multi-tenancy, data encryption, and security audits for compliance, which are not available in the open-source version. +- **Enhanced Dashboard**: Another significant advantage of GreptimeCloud is its superior dashboard, which is more user-friendly and includes a unique Prometheus workbench. This workbench facilitates online editing of Prometheus dashboards and alert rules, as well as GitOps integration. +- **Specialized Solutions**: GreptimeCloud introduces specialized solutions like GreptimeAI, which leverages DBaaS technology. We are also expanding our offerings to include more innovative solutions, such as those for IoT. + +As mentioned, the cloud version offers more ready-to-use features to help you get started quickly. The core features are almost identical, especially on our dedicated plan. + +### What should I do if the region becomes `DOWNGRADED` and the tables on that node become read-only after the datanode restarts? Is there a way to automatically reactivate it? + +According to your configuration, the failover in metasrv, which may mark the region as `DOWNGRADED`, is disabled. Another procedure that may mark a region as `DOWNGRADED` is the region migration procedure. Please try running the region migration procedure and provide feedback for further assistance. + +### Is there a guide or suggestions for compiling GreptimeDB into a standalone binary with only the necessary modules and features for an embedded environment? + +We have prebuilt binaries for Android ARM64 platforms, which have been successfully used in some enterprise projects. However, these binaries are not available for bare metal devices, as some fundamental components of GreptimeDB require a standard library. + +### Is there a built-in SQL command like 'compaction table t1' that can be used for manual compaction? + +Of course, please use the `compact_table` function: + +```sql +-- Schedule a compaction for table test -- +ADMIN compact_table("test"); +``` + +There are many [administration functions](/reference/sql/admin.md#admin-functions) for database management. + +### Can GreptimeDB be used to store logs? + +- The current columnar storage structure can be used to store logs. For example, by setting a column's type to string (non-primary key), logs can be stored. Logs can be written and queried using the supported protocols, and the data can be stored in object storage (OSS/S3) with distributed scalability. + +- If logs can be parsed into structured dimensions, they can also be stored as tags (primary key). These tags can then be used for dimensional queries. + +- However, there are still a few key features missing. Firstly, full-text indexing (currently, LIKE queries can be used as a substitute). Secondly, specific syntax or SQL functions for log queries. Lastly, support for some unique log ingestion protocols. These features are under active development and are expected to be supported in version 0.9, anticipated for release in early July. However, it may not be a simple replacement for Elasticsearch (ES) since its query syntax needs further exploration. Currently, SQL is the primary query language. + +### How is the query performance for non-primary key fields? Can inverted indexes be set? Will the storage cost be lower compared to Elasticsearch? + +Currently, non-primary key fields (or non-tag fields) do not have default inverted indexes, and we have not yet provided a `CREATE INDEX` syntax. Inverted index support will be released in an upcoming iteration along with full-text indexing. Without indexes, queries rely on MPP brute-force scanning. Although there is some parallel processing, the efficiency may not be optimal. + +As for storage costs, they will certainly be lower. You can use containers and object storage directly without relying on disks, using small local disks for buffering/caching to speed up performance. GreptimeDB employs a tiered storage architecture. For more details, please refer to our documentation on architecture and storage location. + +### Is the Log-Structured Merge-Tree engine similar to Kafka's engine model? + +From a technical storage perspective, they are similar. However, the actual data formats differ: GreptimeDB reads and writes Parquet format, while Kafka uses its own RecordBatch format. To analyze time-series data temporarily stored in Kafka, it needs to be written into GreptimeDB first. + +You can replace Kafka with EMQX, which is also a message queue. Here is a reference example: [EMQX Data Integration with GreptimeDB](https://www.emqx.com/en). The process of writing data from Kafka to GreptimeDB is quite similar. + +As mentioned, to analyze the data, it must be written into GreptimeDB first. Consume Kafka messages and write them into GreptimeDB using the provided protocols. If analyzing data directly in Kafka is necessary, you might consider the KSQL project: [KSQL GitHub Repository](https://github.com/confluentinc/ksql). However, our past attempts with KSQL encountered several issues. + +We are also working on releasing a Kafka consumer component that will automate the consumption and writing process. + +### Are there limitations on the number of tables or columns in GreptimeDB? Does having many columns affect read and write performance? + +Generally, there are no strict limitations. With a few hundred tables, as long as there aren't many primary key columns, the impact on write performance is minimal (measured by the number of points written per second, not rows). + +Similarly, for reads, if queries only involve a subset of columns, the memory and computational load will not be significantly high. + +### Can tables be dynamically partitioned by day based on timestamps, or is this unnecessary because the timestamp field already has an index? + +GreptimeDB's data is distributed in timestamp order, so there is no need to additionally shard/partition by timestamp. It is recommended to shard by primary key instead. + +### How many servers are generally needed to set up a reliable GreptimeDB cluster, and how should Frontend, Datanode, and Metasrv be deployed? Should each node run all three services regardless of the number of nodes? + +A minimum of 3 nodes is required, with each node running the 3 services: metasrv, frontend, and datanode. However, the exact number of nodes depends on the scale of data being handled. + +It is not necessary to deploy all three services on each node. A small-sized cluster can be set up with 3 nodes dedicated to metasrv. Frontend and datanode can be deployed on equal nodes, with one container running two processes. + +For more general advice for deployment, please read [Capacity Plan](/user-guide/administration/capacity-plan.md). + +### Does GreptimeDB support inverted indexes, and does it use Tantivy? + +Since v0.7, GreptimeDB supports inverted indexes which are designed by ourselves, read the [Contributor Guide](/contributor-guide/datanode/data-persistence-indexing.md#inverted-index) for more information. + +We plan to integrate Tantivy into the upcoming 0.9 release for full-text search functionality, although we are not currently using it. + +### In v0.8, does the Flow Engine (pre-computation) feature support PromQL syntax for calculations? + +This is a good suggestion. Currently, the Flow Engine does not support PromQL syntax for calculations. We will evaluate this, as it seems theoretically feasible. + +### Will Metasrv support storage backends like MySQL or PostgreSQL? + +We have developed an abstraction layer for Metasrv, but it does not yet support RDBMS backends. Support for MySQL and PostgreSQL is planned. For further suggestions, please open an issue on our GitHub repository. + +### What is the best way to downsample interface traffic rates (maximum rate within every hour) from multiple NICs(network interface controller) across thousands of computers every 30 seconds, so that the data can be kept for many years? + +Using a flow table is the appropriate tool for this task. A simple flow task should suffice. The output of a flow task is stored in a normal table, allowing it to be kept indefinitely. + +### Why is there a performance drop in query response times after upgrading or restarting? + +Currently, GreptimeDB only builds indexes for persistent data. Therefore, query performance might improve after flushing buffered input data. The in-memory page cache for persistent files also needs to be warmed up by queries after restarting the instance. + +- Persistence Mechanism: Data is flushed periodically or when the buffered data size reaches a threshold. +- Cache Warm-up: Query performance improves as the in-memory page cache warms up. + +These mechanisms help stabilize and improve query performance after an upgrade. \ No newline at end of file diff --git a/versioned_docs/version-0.7/faq-and-others/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/faq-and-others/overview.md similarity index 86% rename from versioned_docs/version-0.7/faq-and-others/overview.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/faq-and-others/overview.md index 82317260e..abbc87d98 100644 --- a/versioned_docs/version-0.7/faq-and-others/overview.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/faq-and-others/overview.md @@ -1,3 +1,3 @@ -# FAQ and others +# 概述 In this section, we present the [most frequently asked questions](./faq.md) and some additional information. diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/getting-started/installation/greptimedb-cluster.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/getting-started/installation/greptimedb-cluster.md new file mode 100644 index 000000000..3a2ec7f1a --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/getting-started/installation/greptimedb-cluster.md @@ -0,0 +1,55 @@ +--- +keywords: [分布式集群, Kubernetes, Docker Compose, 水平扩展, 快速开始] +description: 介绍如何在 Kubernetes 和 Docker Compose 中部署 GreptimeDB 集群,以支持水平扩展。 +--- + +# GreptimeDB 分布式集群 + +GreptimeDB 可以运行于 [cluster](/contributor-guide/overview.md) 模式以支持水平扩展。 + +## 在 Kubernetes 中部署 GreptimeDB 集群 + +对于生产环境,我们建议在 Kubernetes 中部署 GreptimeDB 集群。请参考 [在 Kubernetes 上部署](/user-guide/deployments/deploy-on-kubernetes/overview.md)。 + +## 使用 Docker Compose + +:::tip 注意 +虽然 Docker Compose 是运行 GreptimeDB 集群的便捷方法,但仅适用于开发和测试目的。 + +对于生产环境或基准测试,我们建议使用 Kubernetes。 +::: + +### 前置条件 + +使用 Docker Compose 是运行 GreptimeDB 集群的最简单方法。开始之前,请确保已经安装了 Docker。 + +### 步骤 1: 下载 Docker Compose 的 YAML 文件 + +``` +wget https://raw.githubusercontent.com/GreptimeTeam/greptimedb/VAR::greptimedbVersion/docker/docker-compose/cluster-with-etcd.yaml +``` + +### 步骤 2: 启动集群 + +``` +GREPTIMEDB_VERSION=VAR::greptimedbVersion \ +GREPTIMEDB_REGISTRY=greptime-registry.cn-hangzhou.cr.aliyuncs.com \ +ETCD_REGISTRY=greptime-registry.cn-hangzhou.cr.aliyuncs.com \ + docker compose -f ./cluster-with-etcd.yaml up +``` + +如果集群成功启动,它将监听 4000-4003 端口。你可以通过参考 [快速开始](../quick-start.md#连接到-greptimedb) 访问集群。 + +### 清理 + +你可以使用以下命令停止集群: + +``` +docker compose -f ./cluster-with-etcd.yaml down +``` + +默认情况下,数据将被存储在 `/tmp/greptimedb-cluster-docker-compose`。如果你想清理数据,也可删除该目录。 + +## 下一步 + +学习如何使用 GreptimeDB:[快速开始](../quick-start.md#连接到-greptimedb)。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/getting-started/installation/greptimedb-dashboard.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/getting-started/installation/greptimedb-dashboard.md similarity index 82% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7/getting-started/installation/greptimedb-dashboard.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/getting-started/installation/greptimedb-dashboard.md index 363093f32..d9674647b 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/getting-started/installation/greptimedb-dashboard.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/getting-started/installation/greptimedb-dashboard.md @@ -1,3 +1,8 @@ +--- +keywords: [控制台, 数据可视化, 查询语言, SQL 查询, PromQL 查询] +description: 介绍 GreptimeDB 控制台的功能和使用方法,包括数据可视化和多种查询语言的支持。 +--- + # GreptimeDB 控制台 数据可视化在时间序列数据分析时发挥着关键作用。为了帮助用户充分利用 GreptimeDB 的各种功能,GreptimeDB 提供了一个简单的[控制台](https://github.com/GreptimeTeam/dashboard)。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/getting-started/installation/greptimedb-standalone.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/getting-started/installation/greptimedb-standalone.md new file mode 100644 index 000000000..01ced0e7e --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/getting-started/installation/greptimedb-standalone.md @@ -0,0 +1,133 @@ +--- +keywords: [单机模式, 二进制安装, Docker, Windows, 配置文档] +description: 介绍如何在单机模式下安装和运行 GreptimeDB,包括使用二进制文件、Docker 和 Windows 的安装方法。 +--- + +# GreptimeDB 单机模式 + +## 安装 + +我们先通过最简单的配置来开始。有关 GreptimeDB 中可用的所有配置选项的详细列表,请参考[配置文档](/user-guide/deployments/configuration.md)。 + +### 二进制 + +你可以在[下载页面](https://greptime.cn/download)通过发布的最新稳定版本尝试使用 GreptimeDB。 + +### Linux 或 macOS + +如果你使用的是 Linux 或 macOS,可以通过以下命令下载 `greptime` binary 的最新版本: + +```shell +curl -fsSL \ + https://raw.githubusercontent.com/greptimeteam/greptimedb/main/scripts/install.sh | sh -s VAR::greptimedbVersion +``` + +下载完成后,binary 文件 `greptime` 将存储在当前的目录中。 + +你可以在单机模式下运行 GreptimeDB: + +```shell +./greptime standalone start +``` + +### Windows + +若您的 Windows 系统已开启 WSL([Windows Subsystem for Linux](https://learn.microsoft.com/en-us/windows/wsl/about)),您可以直接打开一个最新的 Ubuntu 接着如上所示运行 GreptimeDB ! + +否则请到我们的[官网](https://greptime.com/resources)下载并解压最新的 GreptimeDB for Windows 安装包。 + +在单机模式下运行 GreptimeDB,您可以在 GreptimeDB 二进制所在的文件夹下打开一个终端(比如 Powershell ),执行: + +```shell +.\greptime standalone start +``` + +### Docker + +请确保已经安装了 [Docker](https://www.docker.com/)。如果还没有安装,可以参考 Docker 官方的[文档](https://www.docker.com/get-started/)进行安装。 + +```shell +docker run -p 127.0.0.1:4000-4003:4000-4003 \ + -v "$(pwd)/greptimedb:/tmp/greptimedb" \ + --name greptime --rm \ + greptime-registry.cn-hangzhou.cr.aliyuncs.com/greptime/greptimedb:VAR::greptimedbVersion standalone start \ + --http-addr 0.0.0.0:4000 \ + --rpc-addr 0.0.0.0:4001 \ + --mysql-addr 0.0.0.0:4002 \ + --postgres-addr 0.0.0.0:4003 +``` + +:::tip 注意事项 +为了防止不小心退出 Docker 容器,你可能想以 “detached” 模式运行它:在 `docker run` 命令中添加 `-d` 参数即可。 +::: + +数据将会存储在当前目录下的 `greptimedb/` 目录中。 + +如果你想要使用另一个版本的 GreptimeDB 镜像,可以从我们的 [GreptimeDB Dockerhub](https://hub.docker.com/r/greptime/greptimedb) 下载。 + +:::tip 注意事项 + +如果正在使用小于 [v23.0](https://docs.docker.com/engine/release-notes/23.0/) 的 Docker 版本,由于旧版本的 Docker Engine 中存在 [bug](https://github.com/moby/moby/pull/42681),所以当你尝试运行上面的命令时,可能会遇到权限不足的问题。 + +你可以: + +1. 设置 `--security-opt seccomp=unconfined`: + + ```shell + docker run --security-opt seccomp=unconfined -p 4000-4003:4000-4003 \ + -v "$(pwd)/greptimedb:/tmp/greptimedb" \ + --name greptime --rm \ + greptime-registry.cn-hangzhou.cr.aliyuncs.com/greptime/greptimedb:VAR::greptimedbVersion standalone start \ + --http-addr 0.0.0.0:4000 \ + --rpc-addr 0.0.0.0:4001 \ + --mysql-addr 0.0.0.0:4002 \ + --postgres-addr 0.0.0.0:4003 + ``` + +2. 将 Docker 版本升级到 v23.0.0 或更高; +::: + +## 绑定地址 + +GreptimeDB 默认绑定地址为 `127.0.0.1`。如果你需要能够接收来自所有地址的连接,可以通过以下参数启动。 + +:::danger 危险操作 + +如果运行 GreptimeDB 的计算机直接向互联网暴露服务,那么绑定 `0.0.0.0` 会十分危险,因为这将数据库实例暴露给互联网上的所有人。 + + + + + +```shell +./greptime standalone start \ + --http-addr 0.0.0.0:4000 \ + --rpc-addr 0.0.0.0:4001 \ + --mysql-addr 0.0.0.0:4002 \ + --postgres-addr 0.0.0.0:4003 +``` + + + + + +```shell +docker run -p 0.0.0.0:4000-4003:4000-4003 \ + -v "$(pwd)/greptimedb:/tmp/greptimedb" \ + --name greptime --rm \ + greptime-registry.cn-hangzhou.cr.aliyuncs.com/greptime/greptimedb:VAR::greptimedbVersion standalone start \ + --http-addr 0.0.0.0:4000 \ + --rpc-addr 0.0.0.0:4001 \ + --mysql-addr 0.0.0.0:4002 \ + --postgres-addr 0.0.0.0:4003 +``` + + + + + +你也可以参考[配置 GreptimeDB](/user-guide/deployments/configuration.md)文档在配置文件中修改绑定的地址。 + +## 下一步 + +学习如何使用 GreptimeDB:[快速开始](../quick-start.md)。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/getting-started/installation/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/getting-started/installation/overview.md new file mode 100644 index 000000000..ab4bc1032 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/getting-started/installation/overview.md @@ -0,0 +1,33 @@ +--- +keywords: [安装, 数据库健康检查, 单机模式, 分布式集群, 快速入门] +description: 介绍如何安装 GreptimeDB 以及启动后检查数据库健康状态的方法。 +--- + +# 概述 + +## 安装 + +根据以下说明安装 GreptimeDB: + +- [GreptimeDB 单机模式](greptimedb-standalone.md) +- [GreptimeDB 分布式集群](greptimedb-cluster.md) + +## 检查数据库健康状态 + +启动 GreptimeDB 后,你可以检查其状态以确保其正常运行。 + +```shell + +curl http://localhost:4000/health + +``` + +如果 GreptimeDB 实例正常运行,你将看到下面的响应: + +```json +{} +``` + +## 下一步 + +- [快速入门](/getting-started/quick-start.md):使用 MySQL 或 PostgreSQL 客户端在 GreptimeDB 中写入和查询数据。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/getting-started/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/getting-started/overview.md similarity index 52% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7/getting-started/overview.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/getting-started/overview.md index 6b94b2fa4..5a8f5232f 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/getting-started/overview.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/getting-started/overview.md @@ -1,6 +1,6 @@ -# 概览 +# 概述 立即开始使用 GreptimeDB! - [安装](./installation/overview.md):安装 GreptimeDB 单机模式或分布式集群。 -- [快速开始](./quick-start/overview.md):使用你熟悉的协议或语言快速上手 GreptimeDB。 +- [快速开始](./quick-start.md):使用你熟悉的协议或语言快速上手 GreptimeDB。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/getting-started/quick-start.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/getting-started/quick-start.md new file mode 100644 index 000000000..3fb23cf53 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/getting-started/quick-start.md @@ -0,0 +1,380 @@ +--- +keywords: [快速开始, 数据库连接, 创建表, 写入数据, 查询数据, 数据可视化] +description: 介绍如何快速开始使用 GreptimeDB,包括连接数据库、创建表、写入数据、查询数据等核心功能。 +--- + +# 快速开始 + +在继续阅读之前,请确保你已经[安装了 GreptimeDB](./installation/overview.md)。 + +本指南通过引导你创建一个 metric 表和一个 log 表来介绍 GreptimeDB 的核心功能。 + +## 连接到 GreptimeDB + +GreptimeDB 支持[多种协议](/user-guide/protocols/overview.md)与数据库进行交互。 +在本快速入门文档中,我们使用 SQL 作为实例。 + +如果你的 GreptimeDB 实例运行在 `127.0.0.1` 中, +并且使用 MySQL 客户端默认端口 `4002` 或 PostgreSQL 客户端默认端口 `4003`, +你可以使用以下命令连接到数据库。 + +GreptimeDB 默认不开启[鉴权认证](/user-guide/deployments/authentication/overview.md)。 +在本章节中你可以在连接数据库时不提供用户名密码。 + +```shell +mysql -h 127.0.0.1 -P 4002 +``` + +或者 + +```shell +psql -h 127.0.0.1 -p 4003 -d public +``` + +## 创建表 + +假设你有一个名为 `grpc_latencies` 的表,用于存储的 gRPC 延迟。表 schema 如下: + +```sql +CREATE TABLE grpc_latencies ( + ts TIMESTAMP TIME INDEX, + host STRING, + method_name STRING, + latency DOUBLE, + PRIMARY KEY (host, method_name) +) with('append_mode'='true'); +``` + +- `ts`:收集指标时的时间戳,时间索引列。 +- `host`:主机名,tag 列。 +- `method_name`:RPC 请求方法的名称,tag 列。 +- `latency`:RPC 请求的延迟。 + +此外,还有一个名为 `app_logs` 的表用于存储日志: + +```sql +CREATE TABLE app_logs ( + ts TIMESTAMP TIME INDEX, + host STRING, + api_path STRING FULLTEXT, + log_level STRING, + log STRING FULLTEXT, + PRIMARY KEY (host, log_level) +) with('append_mode'='true'); +``` + +- `ts`:日志条目的时间戳,时间索引列。 +- `host`:主机名,tag 列。 +- `api_path`:API 路径,使用 `FULLTEXT` 进行索引以加速搜索。 +- `log_level`:日志级别,tag 列。 +- `log`:日志消息,使用 `FULLTEXT` 进行索引以加速搜索。 + +## 写入数据 + +让我们插入一些模拟数据来模拟收集的指标和错误日志。 + +假设有两个服务器 `host1` 和 `host2` 记录着 gRPC 延迟。 +从 `2024-07-11 20:00:10` 开始,`host1` 的延迟显著增加。 + +下图显示了 `host1` 的不稳定延迟。 + +unstable latencies + +使用以下 SQL 语句插入模拟数据。 + +在 `2024-07-11 20:00:10` 之前,主机正常运行: + +```sql +INSERT INTO grpc_latencies (ts, host, method_name, latency) VALUES + ('2024-07-11 20:00:06', 'host1', 'GetUser', 103.0), + ('2024-07-11 20:00:06', 'host2', 'GetUser', 113.0), + ('2024-07-11 20:00:07', 'host1', 'GetUser', 103.5), + ('2024-07-11 20:00:07', 'host2', 'GetUser', 107.0), + ('2024-07-11 20:00:08', 'host1', 'GetUser', 104.0), + ('2024-07-11 20:00:08', 'host2', 'GetUser', 96.0), + ('2024-07-11 20:00:09', 'host1', 'GetUser', 104.5), + ('2024-07-11 20:00:09', 'host2', 'GetUser', 114.0); +``` + +在 `2024-07-11 20:00:10` 之后,`host1` 的延迟变得不稳定: + +```sql + +INSERT INTO grpc_latencies (ts, host, method_name, latency) VALUES + ('2024-07-11 20:00:10', 'host1', 'GetUser', 150.0), + ('2024-07-11 20:00:10', 'host2', 'GetUser', 110.0), + ('2024-07-11 20:00:11', 'host1', 'GetUser', 200.0), + ('2024-07-11 20:00:11', 'host2', 'GetUser', 102.0), + ('2024-07-11 20:00:12', 'host1', 'GetUser', 1000.0), + ('2024-07-11 20:00:12', 'host2', 'GetUser', 108.0), + ('2024-07-11 20:00:13', 'host1', 'GetUser', 80.0), + ('2024-07-11 20:00:13', 'host2', 'GetUser', 111.0), + ('2024-07-11 20:00:14', 'host1', 'GetUser', 4200.0), + ('2024-07-11 20:00:14', 'host2', 'GetUser', 95.0), + ('2024-07-11 20:00:15', 'host1', 'GetUser', 90.0), + ('2024-07-11 20:00:15', 'host2', 'GetUser', 115.0), + ('2024-07-11 20:00:16', 'host1', 'GetUser', 3000.0), + ('2024-07-11 20:00:16', 'host2', 'GetUser', 95.0), + ('2024-07-11 20:00:17', 'host1', 'GetUser', 320.0), + ('2024-07-11 20:00:17', 'host2', 'GetUser', 115.0), + ('2024-07-11 20:00:18', 'host1', 'GetUser', 3500.0), + ('2024-07-11 20:00:18', 'host2', 'GetUser', 95.0), + ('2024-07-11 20:00:19', 'host1', 'GetUser', 100.0), + ('2024-07-11 20:00:19', 'host2', 'GetUser', 115.0), + ('2024-07-11 20:00:20', 'host1', 'GetUser', 2500.0), + ('2024-07-11 20:00:20', 'host2', 'GetUser', 95.0); +``` + +当 `host1` 的 gRPC 请求的延迟遇到问题时,收集了一些错误日志。 + +```sql +INSERT INTO app_logs (ts, host, api_path, log_level, log) VALUES + ('2024-07-11 20:00:10', 'host1', '/api/v1/resource', 'ERROR', 'Connection timeout'), + ('2024-07-11 20:00:10', 'host1', '/api/v1/billings', 'ERROR', 'Connection timeout'), + ('2024-07-11 20:00:11', 'host1', '/api/v1/resource', 'ERROR', 'Database unavailable'), + ('2024-07-11 20:00:11', 'host1', '/api/v1/billings', 'ERROR', 'Database unavailable'), + ('2024-07-11 20:00:12', 'host1', '/api/v1/resource', 'ERROR', 'Service overload'), + ('2024-07-11 20:00:12', 'host1', '/api/v1/billings', 'ERROR', 'Service overload'), + ('2024-07-11 20:00:13', 'host1', '/api/v1/resource', 'ERROR', 'Connection reset'), + ('2024-07-11 20:00:13', 'host1', '/api/v1/billings', 'ERROR', 'Connection reset'), + ('2024-07-11 20:00:14', 'host1', '/api/v1/resource', 'ERROR', 'Timeout'), + ('2024-07-11 20:00:14', 'host1', '/api/v1/billings', 'ERROR', 'Timeout'), + ('2024-07-11 20:00:15', 'host1', '/api/v1/resource', 'ERROR', 'Disk full'), + ('2024-07-11 20:00:15', 'host1', '/api/v1/billings', 'ERROR', 'Disk full'), + ('2024-07-11 20:00:16', 'host1', '/api/v1/resource', 'ERROR', 'Network issue'), + ('2024-07-11 20:00:16', 'host1', '/api/v1/billings', 'ERROR', 'Network issue'); +``` + +## 查询数据 + +### 根据 tag 和时间索引进行过滤 + +你可以使用 WHERE 子句来过滤数据。例如,要查询 `2024-07-11 20:00:15` 之后 `host1` 的延迟: + +```sql +SELECT * + FROM grpc_latencies + WHERE host = 'host1' AND ts > '2024-07-11 20:00:15'; +``` + +```sql ++---------------------+-------+-------------+---------+ +| ts | host | method_name | latency | ++---------------------+-------+-------------+---------+ +| 2024-07-11 20:00:16 | host1 | GetUser | 3000 | +| 2024-07-11 20:00:17 | host1 | GetUser | 320 | +| 2024-07-11 20:00:18 | host1 | GetUser | 3500 | +| 2024-07-11 20:00:19 | host1 | GetUser | 100 | +| 2024-07-11 20:00:20 | host1 | GetUser | 2500 | ++---------------------+-------+-------------+---------+ +5 rows in set (0.14 sec) +``` + +你还可以在过滤数据时使用函数。例如,你可以使用 `approx_percentile_cont` 函数按主机分组计算延迟的第 95 百分位数: + +```sql +SELECT + approx_percentile_cont(latency, 0.95) AS p95_latency, + host +FROM grpc_latencies +WHERE ts >= '2024-07-11 20:00:10' +GROUP BY host; +``` + +```sql ++-------------------+-------+ +| p95_latency | host | ++-------------------+-------+ +| 4164.999999999999 | host1 | +| 115 | host2 | ++-------------------+-------+ +2 rows in set (0.11 sec) +``` + +### Range query + +你可以使用 [range query](/reference/sql/range.md#range-query)来实时监控延迟。例如,按 5 秒窗口计算请求的 p95 延迟: + +```sql +SELECT + ts, + host, + approx_percentile_cont(latency, 0.95) RANGE '5s' AS p95_latency +FROM + grpc_latencies +ALIGN '5s' FILL PREV; +``` + +```sql ++---------------------+-------+-------------+ +| ts | host | p95_latency | ++---------------------+-------+-------------+ +| 2024-07-11 20:00:05 | host2 | 114 | +| 2024-07-11 20:00:10 | host2 | 111 | +| 2024-07-11 20:00:15 | host2 | 115 | +| 2024-07-11 20:00:20 | host2 | 95 | +| 2024-07-11 20:00:05 | host1 | 104.5 | +| 2024-07-11 20:00:10 | host1 | 4200 | +| 2024-07-11 20:00:15 | host1 | 3500 | +| 2024-07-11 20:00:20 | host1 | 2500 | ++---------------------+-------+-------------+ +8 rows in set (0.06 sec) +``` + +### 全文搜索 + +你可以使用 `matches` 函数来搜索具有 `FULLTEXT` 索引的列。例如,搜索包含错误信息 `timeout` 的日志: + +```sql +SELECT + ts, + api_path, + log +FROM + app_logs +WHERE + matches(log, 'timeout'); +``` + +```sql ++---------------------+------------------+--------------------+ +| ts | api_path | log | ++---------------------+------------------+--------------------+ +| 2024-07-11 20:00:10 | /api/v1/billings | Connection timeout | +| 2024-07-11 20:00:10 | /api/v1/resource | Connection timeout | ++---------------------+------------------+--------------------+ +2 rows in set (0.01 sec) +``` + +### 指标和日志的关联查询 + +通过组合两个表的数据,你可以快速地确定故障时间和相应的日志。以下 SQL 查询使用 `JOIN` 操作关联指标和日志: + +```sql +WITH + metrics AS ( + SELECT + ts, + host, + approx_percentile_cont(latency, 0.95) RANGE '5s' AS p95_latency + FROM + grpc_latencies + ALIGN '5s' FILL PREV + ), + logs AS ( + SELECT + ts, + host, + count(log) RANGE '5s' AS num_errors, + FROM + app_logs + WHERE + log_level = 'ERROR' + ALIGN '5s' +) +--- 关联 metric 和日志 --- +SELECT + metrics.ts, + p95_latency, + coalesce(num_errors, 0) as num_errors, + metrics.host +FROM + metrics + LEFT JOIN logs ON metrics.host = logs.host + AND metrics.ts = logs.ts +ORDER BY + metrics.ts; +``` + + +```sql ++---------------------+-------------+------------+-------+ +| ts | p95_latency | num_errors | host | ++---------------------+-------------+------------+-------+ +| 2024-07-11 20:00:05 | 114 | 0 | host2 | +| 2024-07-11 20:00:05 | 104.5 | 0 | host1 | +| 2024-07-11 20:00:10 | 4200 | 10 | host1 | +| 2024-07-11 20:00:10 | 111 | 0 | host2 | +| 2024-07-11 20:00:15 | 115 | 0 | host2 | +| 2024-07-11 20:00:15 | 3500 | 4 | host1 | +| 2024-07-11 20:00:20 | 110 | 0 | host2 | +| 2024-07-11 20:00:20 | 2500 | 0 | host1 | ++---------------------+-------------+------------+-------+ +8 rows in set (0.02 sec) +``` + + + +## GreptimeDB 控制台 + +GreptimeDB 提供了一个[仪表板](./installation/greptimedb-dashboard.md)用于数据探索和管理。 + +### 数据探索 + +按照[安装部分](./installation/overview.md)中的说明启动 GreptimeDB 后,你可以通过 HTTP 地址 `http://localhost:4000/dashboard` 访问控制台。 + +点击 `+` 按钮添加一个新的查询,在命令文本中编写你的 SQL 命令,然后点击 `Run All`。 +下方的 SQL 会查询 `grpc_latencies` 表中的所有数据。 + +```sql +SELECT * FROM grpc_latencies; +``` + +然后点击结果面板中的 `Chart` 按钮来可视化数据。 + +![select gRPC latencies](/select-grpc-latencies.png) + +### 使用 InfluxDB Line Protocol 导入数据 + +除了 SQL,GreptimeDB 还支持多种协议,其中最常用之一是 InfluxDB Line Protocol。 +在仪表板中点击 `Ingest` 图标,你可以以 InfluxDB Line Protocol 格式上传数据。 + +例如,将以下数据粘贴到输入框中: + +```txt +grpc_metrics,host=host1,method_name=GetUser latency=100,code=0 1720728021000000000 +grpc_metrics,host=host2,method_name=GetUser latency=110,code=1 1720728021000000000 +``` + +然后点击 `Write` 按钮来导入数据到 `grpc_metrics` 表。如果改表不存在,将会自动创建该表。 +## 下一步 + +你现在已经体验了 GreptimeDB 的核心功能。 +要进一步探索和利用 GreptimeDB: + +- [使用 Grafana 可视化数据](/user-guide/integrations/grafana.md) +- [探索更多 GreptimeDB 的 Demo](https://github.com/GreptimeTeam/demo-scene/) +- [阅读用户指南文档以了解更多关于 GreptimeDB 的详细信息](/user-guide/overview.md) + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/getting-started/create-service.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/getting-started/create-service.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/getting-started/create-service.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/getting-started/create-service.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/getting-started/go.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/getting-started/go.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/getting-started/go.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/getting-started/go.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/getting-started/influxdb.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/getting-started/influxdb.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/getting-started/influxdb.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/getting-started/influxdb.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/getting-started/java.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/getting-started/java.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/getting-started/java.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/getting-started/java.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/getting-started/mysql.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/getting-started/mysql.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/getting-started/mysql.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/getting-started/mysql.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/getting-started/node.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/getting-started/node.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/getting-started/node.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/getting-started/node.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/getting-started/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/getting-started/overview.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/getting-started/overview.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/getting-started/overview.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/getting-started/prometheus.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/getting-started/prometheus.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/getting-started/prometheus.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/getting-started/prometheus.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/getting-started/python.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/getting-started/python.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/getting-started/python.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/getting-started/python.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/getting-started/vector.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/getting-started/vector.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/getting-started/vector.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/getting-started/vector.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/getting-started/visualize-data.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/getting-started/visualize-data.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/getting-started/visualize-data.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/getting-started/visualize-data.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/integrations/alloy.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/integrations/alloy.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/integrations/alloy.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/integrations/alloy.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/integrations/dbeaver.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/integrations/dbeaver.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/integrations/dbeaver.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/integrations/dbeaver.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/integrations/grafana.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/integrations/grafana.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/integrations/grafana.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/integrations/grafana.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/integrations/influxdb.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/integrations/influxdb.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/integrations/influxdb.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/integrations/influxdb.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/integrations/kafka.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/integrations/kafka.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/integrations/kafka.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/integrations/kafka.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/integrations/metabase.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/integrations/metabase.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/integrations/metabase.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/integrations/metabase.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/integrations/mindsdb.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/integrations/mindsdb.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/integrations/mindsdb.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/integrations/mindsdb.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/integrations/mysql.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/integrations/mysql.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/integrations/mysql.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/integrations/mysql.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/integrations/otlp.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/integrations/otlp.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/integrations/otlp.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/integrations/otlp.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/integrations/postgresql.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/integrations/postgresql.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/integrations/postgresql.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/integrations/postgresql.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/integrations/prometheus.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/integrations/prometheus.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/integrations/prometheus.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/integrations/prometheus.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/integrations/sdk-libraries/go.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/integrations/sdk-libraries/go.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/integrations/sdk-libraries/go.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/integrations/sdk-libraries/go.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/integrations/sdk-libraries/java.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/integrations/sdk-libraries/java.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/integrations/sdk-libraries/java.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/integrations/sdk-libraries/java.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/integrations/streamlit.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/integrations/streamlit.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/integrations/streamlit.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/integrations/streamlit.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/integrations/superset.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/integrations/superset.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/integrations/superset.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/integrations/superset.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/integrations/vector.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/integrations/vector.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/integrations/vector.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/integrations/vector.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/migrate-to-greptimecloud/migrate-from-influxdb.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/migrate-to-greptimecloud/migrate-from-influxdb.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/migrate-to-greptimecloud/migrate-from-influxdb.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/migrate-to-greptimecloud/migrate-from-influxdb.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/migrate-to-greptimecloud/migrate-from-prometheus.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/migrate-to-greptimecloud/migrate-from-prometheus.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/migrate-to-greptimecloud/migrate-from-prometheus.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/migrate-to-greptimecloud/migrate-from-prometheus.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/overview.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/overview.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/overview.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/tutorials/monitor-host-metrics/go.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/tutorials/monitor-host-metrics/go.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/tutorials/monitor-host-metrics/go.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/tutorials/monitor-host-metrics/go.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/tutorials/monitor-host-metrics/influxdb.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/tutorials/monitor-host-metrics/influxdb.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/tutorials/monitor-host-metrics/influxdb.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/tutorials/monitor-host-metrics/influxdb.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/tutorials/monitor-host-metrics/java.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/tutorials/monitor-host-metrics/java.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/tutorials/monitor-host-metrics/java.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/tutorials/monitor-host-metrics/java.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/tutorials/monitor-host-metrics/mysql.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/tutorials/monitor-host-metrics/mysql.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/tutorials/monitor-host-metrics/mysql.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/tutorials/monitor-host-metrics/mysql.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/tutorials/monitor-host-metrics/node-js.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/tutorials/monitor-host-metrics/node-js.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/tutorials/monitor-host-metrics/node-js.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/tutorials/monitor-host-metrics/node-js.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/tutorials/monitor-host-metrics/prometheus.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/tutorials/monitor-host-metrics/prometheus.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/tutorials/monitor-host-metrics/prometheus.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/tutorials/monitor-host-metrics/prometheus.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/tutorials/monitor-host-metrics/python.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/tutorials/monitor-host-metrics/python.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/tutorials/monitor-host-metrics/python.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/tutorials/monitor-host-metrics/python.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/tutorials/monitor-host-metrics/visualize-data.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/tutorials/monitor-host-metrics/visualize-data.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/tutorials/monitor-host-metrics/visualize-data.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/tutorials/monitor-host-metrics/visualize-data.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/usage-&-billing/billing.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/usage-&-billing/billing.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/usage-&-billing/billing.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/usage-&-billing/billing.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/usage-&-billing/dedicated.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/usage-&-billing/dedicated.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/usage-&-billing/dedicated.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/usage-&-billing/dedicated.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/usage-&-billing/hobby.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/usage-&-billing/hobby.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/usage-&-billing/hobby.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/usage-&-billing/hobby.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/usage-&-billing/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/usage-&-billing/overview.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/usage-&-billing/overview.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/usage-&-billing/overview.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/usage-&-billing/request-capacity-unit.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/usage-&-billing/request-capacity-unit.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/usage-&-billing/request-capacity-unit.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/usage-&-billing/request-capacity-unit.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/usage-&-billing/serverless.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/usage-&-billing/serverless.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/usage-&-billing/serverless.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/usage-&-billing/serverless.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/usage-&-billing/shared-storage-capacity.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/usage-&-billing/shared-storage-capacity.md similarity index 100% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.11/greptimecloud/usage-&-billing/shared-storage-capacity.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/greptimecloud/usage-&-billing/shared-storage-capacity.md diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/index.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/index.md similarity index 66% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7/index.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/index.md index 021d69a4d..b0610552f 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/index.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/index.md @@ -1,20 +1,25 @@ +--- +keywords: [时序数据库, 开源时序数据库, 时序数据, 可观测性工具, 云原生数据库, 数据可观测性, 可观测性平台, 边缘数据库, 物联网边缘计算, 边缘云计算, 日志管理, 日志聚合, 高基数, SQL查询示例, OpenTelemetry 收集器, GreptimeDB] +description: 介绍了 GreptimeDB 的核心功能和特点,并提供了相关文档的链接,帮助用户快速上手和深入了解。 +--- + # 简介

GreptimeDB Logo

-GreptimeDB 是开源的时序数据库,注重效率、可扩展性和分析能力。GreptimeDB 可以在云时代的基础设施上工作,使用户受益于良好的灵活性和高性价比的存储。 +GreptimeDB 是开源的统一时序数据库,能同时处理**指标**(Metrics)、**日志**(Logs)、**事件**(Events)和**追踪**(Traces)。从云到端,GreptimeDB 能从任意规模的时序数据中获取实时数据洞察。 GreptimeDB 经由 [GreptimeCloud](https://greptime.cn/product/cloud) 提供云服务。 GreptimeCloud 是一个完全托管的时序数据库服务,具有无服务器的可扩展性、与生态系统的无缝集成和 Prometheus 兼容性。 我们的核心开发人员多年深耕于建立时序数据平台。基于他们的丰富经验,GreptimeDB 应运而生,并为用户提供: +- 统一的时序数据处理;GreptimeDB 将所有时序数据统一抽象成带有时间戳和上下文的事件,从而统一了指标、日志和事件的存储和分析。同时,GreptimeDB 支持使用 SQL 和 PromQL 进行分析,以及通过持续聚合能力来实现流处理。 - 为处理时序数据而优化的列式布局;经过压缩、整理,并存储在各种存储后端,尤其是可以节省 50 倍成本效率的云对象存储。 - 完全开源的分布式集群架构,利用云原生弹性计算资源的强大功能。 - 从边缘节点的单机部署到云端强大、高可用的分布式集群的无缝扩展,为开发人员和管理员提供透明的体验。 -- 原生 SQL 和 PromQL 的查询支持,以及便于复杂的分析任务的 Python 脚本。 - 灵活的索引功能和分布式、并行处理查询引擎,解决高基数的问题。 - 适配广泛采用的数据库协议和 API,包括 MySQL、PostgreSQL 和 Prometheus 远程存储等。 - Schemaless 写入,自动为数据创建表格。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/about-greptimedb-version.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/about-greptimedb-version.md new file mode 100644 index 000000000..ab041813b --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/about-greptimedb-version.md @@ -0,0 +1,34 @@ +--- +keywords: [版本号, 语义化版本控制, 主版本号, 次版本号, 修订号] +description: 介绍 GreptimeDB 版本号的语义化版本控制方案,包括主版本号、次版本号和修订号的定义和影响。 +--- + +# 关于 GreptimeDB 版本号 + +GreptimeDB 遵循 [语义化版本控制](https://semver.org/) 方案: + +1.2.3 其中: +- 1 是主版本号 +- 2 是次版本号 +- 3 是修订号 + +## 主版本号(1) + +主版本号表示软件生命周期中的一个重要里程碑,通常引入广泛的变化。 +- 特点:包括主要的架构更新、重大新功能或系统大修。 +- 影响:通常不向后兼容,用户或开发人员需要进行调整。 +- 示例:主要的 API 重新设计、基础架构的重大变化或引入新的核心模块。 + +## 次版本号(2) + +次版本号侧重于功能增强和小改进,旨在完善现有系统。 +- 特点:添加新功能、小更新或界面改进。 +- 影响:虽然它在同一主版本内努力保持向后兼容,但偶尔也可能会出现小的破坏性更改。 +- 示例:引入可选功能、更新用户界面或扩展配置选项并对现有行为进行轻微调整。 + +## 修订号(3) + +修订号用于修补或小幅改进,解决特定问题。 +- 特点:专注于错误修复、安全更新或性能优化。 +- 影响:不引入新功能或改变系统的整体行为。 +- 示例:修复已知错误、解决安全漏洞或提高系统稳定性。 \ No newline at end of file diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/command-lines.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/command-lines.md new file mode 100644 index 000000000..ff70b94bf --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/command-lines.md @@ -0,0 +1,205 @@ +--- +keywords: [命令行工具, 安装 Greptime, 启动服务, 配置示例, 升级版本] +description: 介绍 Greptime 命令行工具的安装、使用方法,包括全局选项、各子命令选项、配置示例、升级 GreptimeDB 版本等内容。 +--- + +# Greptime 命令行工具 + +`greptime` 命令行工具可以启动、停止、或传递配置项给 GreptimeDB。 + +## 安装命令行工具 + +Greptime 命令行工具与 GreptimeDB 二进制文件捆绑在一起。 +在[安装 GreptimeDB](/getting-started/installation/overview.md)之后, +你可以在 GreptimeDB 的当前目录中执行 `./greptime` 命令。 + +为了方便起见,如果你希望使用 `greptime` 而不是 `./greptime` 来运行命令, +可以将命令行工具的二进制文件移动到系统的 `bin` 目录,或者将二进制文件的路径添加到 `PATH` 环境变量中。 + +## 选项 + +`help` 命令列出了 `greptime` 所有可用的命令和选项。 + +```sh +$ greptime help +Usage: greptime [OPTIONS] + +Commands: + datanode Start datanode service + frontend Start frontend service + metasrv Start metasrv service + standalone Run greptimedb as a standalone service + cli Execute the cli tools for greptimedb + help Print this message or the help of the given subcommand(s) + +Options: + --log-dir + --log-level + -h, --help Print help + -V, --version Print version +``` + +- `--log-dir=[dir]` specify logs directory, `/tmp/greptimedb/logs` by default. +- `--log-level=[info | debug | error | warn | trace]` specify the log level, `info` by default. + +### 全局选项 + +- `-h`/`--help`: 打印命令行帮助信息 +- `-V`/`--version`: 打印 GreptimeDB 版本信息 +- `--log-dir `: 指定日志路径 +- `--log-level `: 指定日志级别,如 `info`、`debug` 等。 + +### datanode 子命令选项 + +通过执行下列命令来获取 `datanode` 子命令的帮助菜单: + +``` +greptime datanode start --help +``` + +- `-c`/`--config-file`: 指定 datanode 启动的配置文件 +- `--data-home`: 数据库存储 home 目录 +- `--env-prefix `: 配置的环境变量前缀,默认为 `GREPTIMEDB_DATANODE`; +- `--http-addr `: HTTP 服务地址 +- `--http-timeout `: HTTP 超时设置,单位秒 +- `--metasrv-addrs `: Metasrv 服务器列表,用逗号或者空格隔开 +- `--node-id `: 节点 ID +- `--rpc-addr `: gRPC 服务地址 +- `--rpc-hostname `: 节点 hostname +- `--wal-dir `: WAL 日志目录; + +所有的地址类选项都是 `ip:port` 形式的字符串。 + +### metasrv 子命令选项 + +通过执行下列命令来获取 `metasrv` 子命令的帮助菜单: + +``` +greptime metasrv start --help +``` + +- `-c`/`--config-file`: 指定 `metasrv` 启动配置文件 +- `--enable-region-failover`: 是否启动 region 自动容灾,默认为 `false` 不启用。 +- `--env-prefix `: 配置的环境变量前缀,默认为`GREPTIMEDB_METASRV`; +- `--bind-addr `:服务监听地址,默认为 `127.0.0.1:3002`. +- `--http-addr `: HTTP 服务器地址 +- `--http-timeout `: HTTP 超时设置,单位秒 +- `--selector `: 参考 [selector 类型](/contributor-guide/metasrv/selector.md#selector-type); +- `--server-addr `: 提供给 frontend 和 datanode 的外部通讯服务器地址 +- `--store-addrs `: 逗号或空格分隔的键值存储服务器(默认为 etcd)地址,用于存储元数据; +- `--use-memory-store`: 是否使用内存存储替代 etcd,仅用于测试 + +### frontend 子命令选项 + +通过执行下列命令来获取 `frontend` 子命令的帮助菜单: + +``` +greptime frontend start --help +``` + +- `-c`/`--config-file`: 指定 `frontend` 启动配置文件 +- `--disable-dashboard`: 是否禁用 dashboard,默认为 `false`。 +- `--env-prefix `: 配置的环境变量前缀,默认为`GREPTIMEDB_FRONTEND`; +- `--rpc-addr `: gRPC 服务地址 +- `--http-addr `: HTTP 服务器地址 +- `--http-timeout `: HTTP 超时设置,单位秒 +- `--influxdb-enable`: 是否启用 `influxdb` HTTP 接口,默认为 true。 +- `--metasrv-addrs `: Metasrv 地址列表,用逗号或者空格隔开 +- `--mysql-addr `: MySQL 服务地址 +- `--postgres-addr `: Postgres 服务地址 +- `--tls-cert-path `: TLS 公钥文件地址 +- `--tls-key-path `: TLS 私钥文件地址 +- `--tls-mode `: TLS 模式 +- `--user-provider `: 参考 [鉴权](/user-guide/deployments/authentication/overview.md); + + +### Flownode 子命令选项 + +通过执行下列命令来获取 `flownode` 子命令的帮助菜单: + +``` +greptime flownode start --help +``` + +- `--node-id `: Flownode的ID +- `--rpc-addr `: gRPC服务器的绑定地址 +- `--rpc-hostname `: gRPC服务器的主机名 +- `--metasrv-addrs ...`: Metasrv地址列表 +- `-c, --config-file `: Flownode的配置文件 +- `--env-prefix `: 环境变量的前缀,默认为 `GREPTIMEDB_FLOWNODE` + +### standalone 子命令选项 + +通过执行下列命令来获取 `standalone` 子命令的帮助菜单: + +``` +greptime standalone start --help +``` + +- `-c`/`--config-file`: 指定 `standalone` 启动配置文件 +- `--env-prefix `: 配置的环境变量前缀,默认为`GREPTIMEDB_STANDALONE`; +- `--http-addr `: HTTP 服务器地址 +- `--influxdb-enable`: 是否启用 `influxdb` HTTP 接口,默认为 true。 +- `--mysql-addr `: MySQL 服务地址 +- `--postgres-addr `: Postgres 服务地址 +- `--rpc-addr `: gRPC 服务地址 + +## 配置示例 + +### 启动服务时使用相关配置 + +使用自定义配置以 standalone 模式启动 GreptimeDB: + +```sh +greptime --log-dir=/tmp/greptimedb/logs --log-level=info standalone start -c config/standalone.example.toml +``` + +`standalone.example.toml` 配置文件来自 `[GreptimeDB](https://github.com/GreptimeTeam/greptimedb/)` 仓库的 `config` 目录。您可以在那里找到更多示例配置文件。使用 `-c` 选项可以指定配置文件,有关更多信息,更多信息请查看[配置](../user-guide/deployments/configuration.md)。 + +为了以分布式模式启动 GreptimeDB,您需要分别启动每个组件。以下命令显示了如何使用自定义配置或命令行参数启动每个组件: + +使用自定义配置启动 metasrv: + +```sh +greptime metasrv start -c config/metasrv.example.toml +``` + +使用自定义配置启动 datanode: + +```sh +greptime datanode start -c config/datanode.example.toml +``` + +使用命令行参数启动 datanode,指定 gRPC 服务地址、MySQL 服务地址、metasrv 地址和该 datanode 的 ID: + +```sh +greptime datanode start --rpc-addr=0.0.0.0:4001 --mysql-addr=0.0.0.0:4002 --metasrv-addrs=0.0.0.0:3002 --node-id=1 +``` + +使用自定义配置启动 frontend: + +```sh +greptime frontend start -c config/frontend.example.toml +``` + +使用命令行参数启动 frontend,指定 metasrv 的地址: + +```sh +greptime frontend start --metasrv-addrs=0.0.0.0:3002 +``` + +使用自定义配置启动 flownode + +```sh +greptime flownode start -c config/flownode.example.toml +``` + +使用命令行参数启动 flownode,指定 metasrv 和 frontend 的地址: + +```sh +greptime flownode start --node-id=0 --rpc-addr=127.0.0.1:6800 --metasrv-addrs=127.0.0.1:3002; +``` + +### 升级 GreptimeDB 版本 + +请参考具体的[升级步骤](/user-guide/administration/upgrade.md) diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/user-guide/operations/gtctl.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/gtctl.md similarity index 95% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7/user-guide/operations/gtctl.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/gtctl.md index 47a036fe3..5ba0e2862 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/user-guide/operations/gtctl.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/gtctl.md @@ -1,3 +1,8 @@ +--- +keywords: [gtctl, 安装, Homebrew, 源代码构建, 自动补全, 快速入门, 部署, Kubernetes, 裸机模式] +description: 介绍 gtctl 工具的安装、使用方法,包括一键安装、通过 Homebrew 安装、从源代码构建、启用自动补全、快速入门、部署等内容。 +--- + # gtctl [gtctl][1],g-t-control,是一个用于管理 GreptimeDB 集群的命令行工具。gtctl 是集成了 GreptimeDB 集群的多种操作的多合一 binary。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/http-endpoints.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/http-endpoints.md new file mode 100644 index 000000000..4a5c6c7d9 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/http-endpoints.md @@ -0,0 +1,198 @@ +--- +keywords: [HTTP API, 管理 API, 健康检查, 状态, 指标, 配置, 仪表盘, 日志级别, 性能分析] +description: 介绍 GreptimeDB 中各种 HTTP 路径及其用法的完整列表。 +--- + +# HTTP API 端点列表 + +以下是 GreptimeDB 中各种 HTTP 路径及其用法的完整列表: + +## 管理 API + +未版本化的端点(不在 `/v1` 下)。用于健康检查、状态、指标等管理用途。 + +### 健康检查 + +- **路径**: `/health` +- **方法**: `GET`, `POST` +- **描述**: 提供一个健康检查端点以验证服务器是否正在运行。 +- **用法**: 访问此端点以检查服务器的健康状态。 + +### 状态 + +- **路径**: `/status` +- **方法**: `GET` +- **描述**: 检索服务器的当前状态。 +- **用法**: 使用此端点获取服务器状态信息。 + +### 指标 + +- **路径**: `/metrics` +- **方法**: `GET` +- **描述**: 暴露 Prometheus 指标以进行监控。 +- **用法**: Prometheus 可以抓取此端点以收集指标数据。 + +### 配置 + +- **路径**: `/config` +- **方法**: `GET` +- **描述**: 检索服务器的配置选项。 +- **用法**: 访问此端点以获取配置详细信息。 + +### 仪表盘 + +- **路径**: `/dashboard` +- **方法**: `GET`, `POST` +- **描述**: 提供对服务器仪表盘界面的访问。 +- **用法**: 访问这些端点以与基于 Web 的仪表盘进行交互。 + +此仪表盘与 GreptimeDB 服务器一起打包,并提供一个用户友好的界面与服务器进行交互。构建 GreptimeDB 时需要启用相应的编译标志。仪表盘的原始源代码在 https://github.com/GreptimeTeam/dashboard。 + +### 日志级别 + +- **路径**: `/debug/log_level` +- **方法**: `POST` +- **描述**: 动态调整服务器的日志级别。 +- **用法**: 发送日志级别更改请求到此端点。 + +有关更多信息,请参阅[如何文档](https://github.com/GreptimeTeam/greptimedb/blob/main/docs/how-to/how-to-change-log-level-on-the-fly.md)。 + +### 性能分析工具 + +- **基础路径**: `/debug/prof/` +- **端点**: + - `cpu` + - `mem` +- **方法**: `POST` 用于分析数据库节点。 +- **描述**: 运行时 CPU 或内存使用情况分析。 +- **用法**: + - 有关 CPU 分析的详细指南,请参阅 [CPU 分析](https://github.com/GreptimeTeam/greptimedb/blob/main/docs/how-to/how-to-profile-cpu.md)。 + - 有关内存分析的详细指南,请参阅 [内存分析](https://github.com/GreptimeTeam/greptimedb/blob/main/docs/how-to/how-to-profile-memory.md)。 + +## 查询端点 + +用于向 GreptimeDB 发送查询的各种查询 API。 + +### SQL API + +- **路径**: `/v1/sql` +- **方法**: `GET`, `POST` +- **描述**: 执行 SQL 查询。 +- **用法**: 在请求体中发送 SQL 语句。 + +有关 SQL API 的更多信息,请参阅用户指南中的 [HTTP API 文档](/user-guide/protocols/http.md#post-sql-statements)。 + +### PromQL API + +- **路径**: `/v1/promql` +- **方法**: `GET`, `POST` +- **描述**: 执行 PromQL 查询以获取 Prometheus 兼容的指标,并以 GreptimeDB 的 JSON 格式返回数据。 +- **用法**: 在请求体中发送 PromQL 语句。 + +有关 PromQL API 的更多信息,请参阅 [PromQL 文档](/user-guide/query-data/promql.md)。 + +## 协议端点 + +与 GreptimeDB 兼容的各种协议的端点。如 InfluxDB、Prometheus、OpenTelemetry 等。 + +### InfluxDB 兼容性 + +- **路径**: + - `/v1/influxdb/write` + - `/v1/influxdb/api/v2/write` + - `/v1/influxdb/ping` + - `/v1/influxdb/health` +- **方法**: + - `POST` 用于写入端点。 + - `GET` 用于 ping 和健康检查端点。 +- **描述**: 提供与 InfluxDB 兼容的数据写入和健康检查端点。 +- **用法**: + - 使用 InfluxDB 行协议写入数据。 + - 使用 ping 和健康检查端点检查服务器状态。 + +有关 InfluxDB 协议的详细文档,请参阅[这里](/user-guide/protocols/influxdb-line-protocol.md)。 + +### Prometheus 远程写入/读取 + +- **路径**: + - `/v1/prometheus/write` + - `/v1/prometheus/read` +- **方法**: `POST` +- **描述**: 支持 Prometheus 远程写入和读取 API。 +- **用法**: + - 使用 Prometheus 远程写入协议发送指标数据。 + - 使用 Prometheus 远程读取协议读取指标数据。 + +### Prometheus HTTP API + +- **基础路径**: `/v1/prometheus/api/v1` +- **端点**: + - `/format_query` + - `/status/buildinfo` + - `/query` + - `/query_range` + - `/labels` + - `/series` + - `/parse_query` + - `/label/{label_name}/values` +- **方法**: `GET`, `POST` +- **描述**: 提供 Prometheus HTTP API 端点以查询和检索指标数据。 +- **用法**: 使用这些端点以标准 Prometheus HTTP API 进行指标交互。 + +有关 Prometheus HTTP API 的更多信息,请参阅原始 Prometheus 文档 [Prometheus HTTP API](https://prometheus.io/docs/prometheus/latest/querying/api/)。 + +### OpenTelemetry 协议 (OTLP) + +- **路径**: + - `/v1/otlp/v1/metrics` + - `/v1/otlp/v1/traces` + - `/v1/otlp/v1/logs` +- **方法**: `POST` +- **描述**: 支持 OpenTelemetry 协议以写入 Metrics、Traces 和 Logs。 +- **用法**: 将 OpenTelemetry 格式的数据发送到这些端点。 + +### Loki 兼容性 + +- **路径**: `/v1/loki/api/v1/push` +- **方法**: `POST` +- **描述**: 以兼容 Loki 的 API 写入日志。 +- **用法**: 将日志数据以 Loki 的格式发送到此端点。 + +### OpenTSDB 协议 + +- **路径**: `/v1/opentsdb/api/put` +- **方法**: `POST` +- **描述**: 支持使用 OpenTSDB 协议写入数据。 +- **用法**: 使用 OpenTSDB 的 JSON 格式写入时间序列数据。 + +## 日志写入端点 + +- **路径**: + - `/v1/events/logs` + - `/v1/events/pipelines/{pipeline_name}` + - `/v1/events/pipelines/dryrun` +- **方法**: + - `POST` 写入日志和添加 Pipeline。 + - `DELETE` 用于删除 Pipeline。 +- **描述**: 提供日志写入和 Pipeline 管理的端点。 +- **用法**: + - 通过 `/logs` 端点写入日志。 + - 使用 `/pipelines` 端点管理日志 Pipeline。 + +有关日志写入和 Pipeline 管理的更多信息,请参阅[日志概述](/user-guide/logs/overview.md)。 + +## 脚本端点 + +### 脚本管理 + +- **路径**: `/v1/scripts` +- **方法**: `POST` +- **描述**: 管理服务器上的脚本。 +- **用法**: 提交脚本以执行或管理。 + +### 运行脚本 + +- **路径**: `/v1/run-script` +- **方法**: `POST` +- **描述**: 在服务器上执行脚本。 +- **用法**: 发送要执行的脚本内容。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql-tools.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql-tools.md new file mode 100644 index 000000000..d7c30ded2 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql-tools.md @@ -0,0 +1,290 @@ +--- +keywords: [SQL 工具, 查询库, 编程语言 Driver, 数据库连接, Raw SQL, 命令行工具, GUI 工具, HTTP API] +description: 介绍如何使用 SQL 工具与 GreptimeDB 交互,包括推荐的查询库、安装方法、连接数据库、使用 Raw SQL 查询数据等内容。 +--- + +# SQL 工具 + +GreptimeDB 使用 SQL 作为主要查询语言,并支持许多流行的 SQL 工具。 +本文档指导你如何使用 SQL 工具与 GreptimeDB 交互。 + +## 编程语言 Driver + +推荐使用成熟的 SQL driver 来查询数据。 + +### 推荐的查询库 + + + + Java 数据库连接(JDBC)是 JavaSoft 规范的标准应用程序编程接口(API),它允许 Java 程序访问数据库管理系统。 + + 许多数据库协议,如 MySQL 或 PostgreSQL,都已经基于 JDBC API 实现了自己的驱动程序。 + 由于 GreptimeDB [支持多种协议](/user-guide/protocols/overview.md),这里我们使用 MySQL 协议作为示例来演示如何使用 JDBC。 + 如果你希望使用其他协议,只需要将 MySQL driver 换为相应的 driver。 + + + 推荐使用 [GORM](https://gorm.io/) 库来查询数据。 + + + +### 安装 + + + + 如果你使用的是 [Maven](https://maven.apache.org/),请将以下内容添加到 `pom.xml` 的依赖项列表中: + + ```xml + + mysql + mysql-connector-java + 8.0.33 + + ``` + + + + 使用下方的命令安装 GORM: + + ```shell + go get -u gorm.io/gorm + ``` + + 以 MySQL 为例安装 driver: + + ```shell + go get -u gorm.io/driver/mysql + ``` + + 将库引入到代码中: + + ```go + import ( + "gorm.io/gorm" + "gorm.io/driver/mysql" + ) + ``` + + + +### Connect to database + +下面以 MySQL 为例演示如何连接到 GreptimeDB。 + + + + ```java + public static Connection getConnection() throws IOException, ClassNotFoundException, SQLException { + Properties prop = new Properties(); + prop.load(QueryJDBC.class.getResourceAsStream("/db-connection.properties")); + + String dbName = (String) prop.get("db.database-driver"); + String dbConnUrl = (String) prop.get("db.url"); + String dbUserName = (String) prop.get("db.username"); + String dbPassword = (String) prop.get("db.password"); + + Class.forName(dbName); + Connection dbConn = DriverManager.getConnection(dbConnUrl, dbUserName, dbPassword); + + return Objects.requireNonNull(dbConn, "Failed to make connection!"); + } + ``` + + 你需要一个 properties 文件来存储数据库连接信息,将其放在 Resources 目录中并命名为 `db-connection.properties`。文件内容如下: + + ```txt + # DataSource + db.database-driver=com.mysql.cj.jdbc.Driver + db.url=jdbc:mysql://localhost:4002/public + db.username= + db.password= + ``` + + 或者你可以从[这里](https://github.com/GreptimeTeam/greptimedb-ingester-java/blob/main/ingester-example/src/main/resources/db-connection.properties)获取文件。 + + + ```go + type Mysql struct { + Host string + Port string + User string + Password string + Database string + + DB *gorm.DB + } + + m := &Mysql{ + Host: "127.0.0.1", + Port: "4002", // default port for MySQL + User: "username", + Password: "password", + Database: "public", + } + + dsn := fmt.Sprintf("tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", + m.Host, m.Port, m.Database) + dsn = fmt.Sprintf("%s:%s@%s", m.User, m.Password, dsn) + db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{}) + if err != nil { + // error handling + } + m.DB = db + ``` + + + +#### 时区 + + + + 通过设置 URL 参数来设置 JDBC 时区: + + ```txt + jdbc:mysql://127.0.0.1:4002?connectionTimeZone=Asia/Shanghai&forceConnectionTimeZoneToSession=true + ``` + * `connectionTimeZone={LOCAL|SERVER|user-defined-time-zone}` 配置连接时区。 + * `forceConnectionTimeZoneToSession=true` 使 session `time_zone` 变量被设置为 `connectionTimeZone` 指定的值。 + + + 在 DSN 中设置时区。例如,将时区设置为 `Asia/Shanghai`: + + ```go + dsn := fmt.Sprintf("tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local&time_zone=%27Asia%2FShanghai%27", + m.Host, m.Port, m.Database) + ``` + + 更多信息请参考 [MySQL Driver 文档](https://github.com/go-sql-driver/mysql?tab=readme-ov-file#system-variables)。 + + + +### Raw SQL + +推荐使用 Raw SQL 来体验 GreptimeDB 的全部功能。 +下面的例子展示了如何使用 Raw SQL 查询数据: + + + + ```java + try (Connection conn = getConnection()) { + Statement statement = conn.createStatement(); + + // DESC table; + ResultSet rs = statement.executeQuery("DESC cpu_metric"); + LOG.info("Column | Type | Key | Null | Default | Semantic Type "); + while (rs.next()) { + LOG.info("{} | {} | {} | {} | {} | {}", + rs.getString(1), + rs.getString(2), + rs.getString(3), + rs.getString(4), + rs.getString(5), + rs.getString(6)); + } + + // SELECT COUNT(*) FROM cpu_metric; + rs = statement.executeQuery("SELECT COUNT(*) FROM cpu_metric"); + while (rs.next()) { + LOG.info("Count: {}", rs.getInt(1)); + } + + // SELECT * FROM cpu_metric ORDER BY ts DESC LIMIT 5; + rs = statement.executeQuery("SELECT * FROM cpu_metric ORDER BY ts DESC LIMIT 5"); + LOG.info("host | ts | cpu_user | cpu_sys"); + while (rs.next()) { + LOG.info("{} | {} | {} | {}", + rs.getString("host"), + rs.getTimestamp("ts"), + rs.getDouble("cpu_user"), + rs.getDouble("cpu_sys")); + } + } + ``` + + 请参考[此处](https://github.com/GreptimeTeam/greptimedb-ingester-java/blob/main/ingester-example/src/main/java/io/greptime/QueryJDBC.java)获取直接可执行的代码。 + + + The following code declares a GORM object model: + + ```go + type CpuMetric struct { + Host string `gorm:"column:host;primaryKey"` + Ts time.Time `gorm:"column:ts;primaryKey"` + CpuUser float64 `gorm:"column:cpu_user"` + CpuSys float64 `gorm:"column:cpu_sys"` + } + ``` + + 如果你正在使用[高层级 API](/user-guide/ingest-data/for-iot/grpc-sdks/go.md#高层级-api) 来插入数据,你可以在模型中同时声明 GORM 和 GreptimeDB Tag。 + + ```go + type CpuMetric struct { + Host string `gorm:"column:host;primaryKey" greptime:"tag;column:host;type:string"` + Ts time.Time `gorm:"column:ts;primaryKey" greptime:"timestamp;column:ts;type:timestamp;precision:millisecond"` + CpuUser float64 `gorm:"column:cpu_user" greptime:"field;column:cpu_user;type:float64"` + CpuSys float64 `gorm:"column:cpu_sys" greptime:"field;column:cpu_sys;type:float64"` + } + ``` + + 声明表名: + + ```go + func (CpuMetric) TableName() string { + return "cpu_metric" + } + ``` + + 使用 Raw SQL 查询数据: + + ```go + var cpuMetric CpuMetric + db.Raw("SELECT * FROM cpu_metric LIMIT 10").Scan(&result) + ``` + + + +### 查询库参考 + +有关如何使用查询库的更多信息,请参考相应库的文档: + + + + - [JDBC 在线教程](https://docs.oracle.com/javase/tutorial/jdbc/basics/index.html) + + + - [GORM](https://gorm.io/docs/index.html) + + + +## 命令行工具 + +### MySQL + +你可以使用 `mysql` 命令行工具连接到 GreptimeDB。 +请参考 [MySQL 协议](/user-guide/protocols/mysql.md) 文档获取连接信息。 + +连接到服务器后,你可以使用所有 [GreptimeDB SQL 命令](/reference/sql/overview.md)与数据库交互。 + +### PostgreSQL + +你可以使用 `psql` 命令行工具连接到 GreptimeDB。 +请参考 [PostgreSQL 协议](/user-guide/protocols/postgresql.md) 文档获取连接信息。 + +连接到服务器后,你可以使用所有 [GreptimeDB SQL 命令](/reference/sql/overview.md)与数据库交互。 + +## GreptimeDB 控制台 + +你可以在 [Greptime 控制台](/getting-started/installation/greptimedb-dashboard.md)中运行 SQL 并可视化数据。 + +## GUI 工具 + +### DBeaver + +请参考 [DBeaver 集成指南](/user-guide/integrations/dbeaver.md)。 + + + +## HTTP API + +你可以将 POST SQL 到 GreptimeDB HTTP API 以查询数据。 +请参考 [HTTP API](/user-guide/protocols/http.md) 文档获取更多信息。 + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/admin.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/admin.md new file mode 100644 index 000000000..d32de0159 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/admin.md @@ -0,0 +1,33 @@ +--- +keywords: [管理函数, ADMIN 语句, SQL ADMIN, 数据库管理, 表管理, 数据管理] +description: ADMIN 语句用于运行管理函数来管理数据库和数据。 +--- + +# ADMIN + +`ADMIN` 语句用于运行管理函数: + +```sql +ADMIN function(arg1, arg2, ...) +``` + +## 管理函数 + +GreptimeDB 提供了一些管理函数来管理数据库和数据: + +* `flush_table(table_name)` 根据表名将表的 Memtable 刷新到 SST 文件中。 +* `flush_region(region_id)` 根据 Region ID 将 Region 的 Memtable 刷新到 SST 文件中。通过 [PARTITIONS](./information-schema/partitions.md) 表查找 Region ID。 +* `compact_table(table_name, [type], [options])` 为表启动一个 compaction 任务,详细信息请阅读 [compaction](/user-guide/administration/manage-data/compaction.md#严格窗口压缩策略swcs和手动压缩)。 +* `compact_region(region_id)` 为 Region 启动一个 compaction 任务。 +* `migrate_region(region_id, from_peer, to_peer, [timeout])` 在 Datanode 之间迁移 Region,请阅读 [Region Migration](/user-guide/administration/manage-data/region-migration.md)。 +* `procedure_state(procedure_id)` 根据 ID 查询 Procedure 状态。 +* `flush_flow(flow_name)` 将 Flow 的输出刷新到目标接收表。 + +例如: +```sql +-- 刷新表 test -- +admin flush_table("test"); + +-- 为表 test 启动 compaction 任务 -- +admin compact_table("test"); +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/alter.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/alter.md new file mode 100644 index 000000000..51ada9b91 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/alter.md @@ -0,0 +1,184 @@ +--- +keywords: [修改数据库, 修改表, ALTER 语句, SQL ALTER, 数据库设置, 表设置] +description: ALTER 用于修改数据库的设置、表的设置或表的元数据。 +--- + +# ALTER + +`ALTER` 可以用来修改数据库的设置,表的设置或表的元数据,包括: + +* 修改数据库选项 +* 添加/删除/修改列 +* 重命名表 +* 修改表选项 + +## ALTER DATABASE + + +`ALTER DATABASE` 语句可以用来修改数据库的选项。 + +### 语法 + +```sql +ALTER TABLE [db.]table + [ADD COLUMN name type [options] + | DROP COLUMN name + | MODIFY COLUMN name type + | MODIFY COLUMN name SET FULLTEXT [WITH ] + | RENAME name + | SET = [, ...] + | UNSET [, ...] + ] +``` + +当前支持修改以下数据库选项: +- `ttl`: 数据库中数据的默认保留时间。 + +### 示例 + +#### 修改数据库中数据的默认保留时间 + +修改数据库中数据的默认保留时间为 1 天: + +```sql +ALTER DATABASE db SET 'ttl'='1d'; +``` + +取消数据库中数据的默认保留时间设置: + +```sql +ALTER DATABASE db UNSET 'ttl'; +``` + +## ALTER TABLE + +## 语法 + +```sql +ALTER TABLE [db.]table + [ADD COLUMN name type [options] + | DROP COLUMN name + | MODIFY COLUMN name type + | MODIFY COLUMN name SET FULLTEXT [WITH ] + | RENAME name + | SET = [, ...] + ] +``` + +### 示例 + +#### 增加列 + +在表中增加新列: + +```sql +ALTER TABLE monitor ADD COLUMN load_15 double; +``` + +列的定义和 [CREATE](./create.md) 中的定义方式一样。 + +我们可以设置新列的位置。比如放在第一位: + +```sql +ALTER TABLE monitor ADD COLUMN load_15 double FIRST; +``` + +或者放在某个已有列之后: + +```sql +ALTER TABLE monitor ADD COLUMN load_15 double AFTER memory; +``` + +增加一个带默认值的 Tag 列(加入 Primary key 约束): +```sql +ALTER TABLE monitor ADD COLUMN app STRING DEFAULT 'shop' PRIMARY KEY; +``` + + +#### 移除列 + +从表中移除列: + +```sql +ALTER TABLE monitor DROP COLUMN load_15; +``` + +后续的所有查询立刻不能获取到被移除的列。 + +#### 修改列类型 + +修改列的数据类型 + +```sql +ALTER TABLE monitor MODIFY COLUMN load_15 STRING; +``` + +被修改的的列不能是 tag 列(primary key)或 time index 列,同时该列必须允许空值 `NULL` 存在来保证数据能够安全地进行转换(转换失败时返回 `NULL`)。 + +#### 修改表的参数 + +`ALTER TABLE` 语句也可以用来更改表的选项。 +当前支持修改以下表选项: +- `ttl`: 表数据的保留时间。 +- `compaction.twcs.time_window`: TWCS compaction 策略的时间窗口,其值是一个[时间范围字符段](/reference/time-durations.md)。 +- `compaction.twcs.max_output_file_size`: TWCS compaction 策略的最大允许输出文件大小。 +- `compaction.twcs.max_active_window_runs`: TWCS compaction 策略的活跃窗口中最多允许的有序组数量。 +- `compaction.twcs.max_inactive_window_runs`: TWCS compaction 策略的非活跃窗口中最多允许的有序组数量。 +- `compaction.twcs.max_active_window_files`: TWCS compaction 策略的活跃窗口中最多允许的文件数量。 +- `compaction.twcs.max_inactive_window_files`: TWCS compaction 策略的非活跃窗口中最多允许的文件数量。 + + +```sql +ALTER TABLE monitor SET 'ttl'='1d'; + +ALTER TABLE monitor SET 'compaction.twcs.time_window'='2h'; + +ALTER TABLE monitor SET 'compaction.twcs.max_output_file_size'='500MB'; + +ALTER TABLE monitor SET 'compaction.twcs.max_inactive_window_files'='2'; + +ALTER TABLE monitor SET 'compaction.twcs.max_active_window_files'='2'; + +ALTER TABLE monitor SET 'compaction.twcs.max_active_window_runs'='6'; + +ALTER TABLE monitor SET 'compaction.twcs.max_inactive_window_runs'='6'; +``` + +#### 移除设置过的表参数 + +```sql +ALTER TABLE monitor UNSET 'ttl'; +``` + +#### 修改列全文索引选项 + +启用列的全文索引: + +```sql +ALTER TABLE monitor MODIFY COLUMN load_15 SET FULLTEXT WITH (analyzer = 'Chinese', case_sensitive = 'false'); +``` + +在启用列的全文索引时,可以使用 `FULLTEXT WITH` 可以指定以下选项: + +- `analyzer`:设置全文索引的分析器语言,支持 `English` 和 `Chinese`。默认为 `English`。 +- `case_sensitive`:设置全文索引是否区分大小写,支持 `true` 和 `false`。默认为 `false`。 + +与 `CREATE TABLE` 一样,可以不带 `WITH` 选项,全部使用默认值。 + +#### 关闭列的全文索引 + +```sql +ALTER TABLE monitor MODIFY COLUMN load_15 UNSET FULLTEXT; +``` + +修改列的全文索引选项时,列的数据类型必须是字符串类型。 + +当列的全文索引未开启过时,可以启用全文索引,并设置 `analyzer` 和 `case_sensitive` 选项;当列的全文索引选项已经启用时,可以关闭全文索引,**但不能修改选项**。 + +#### 重命名表 + +```sql +ALTER TABLE monitor RENAME monitor_new; +``` + +该命令只是重命名表,不会修改表中的数据。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/case.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/case.md new file mode 100644 index 000000000..9bcb03ca6 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/case.md @@ -0,0 +1,94 @@ +--- +keywords: [条件逻辑, CASE 语句, SQL CASE, 条件查询, 数据检索, SQL 语法] +description: CASE 语句允许在查询中执行条件逻辑,根据条件返回特定值。 +--- + +# CASE + +CASE 语句类似于编程语言中的 IF-THEN-ELSE 结构,允许你在查询中执行条件逻辑, +它使你能够根据条件返回特定值,从而使数据检索和操作更加动态。 + +## 语法 + +```sql +CASE + WHEN condition1 THEN result1 + WHEN condition2 THEN result2 + ... + ELSE result +END +``` + +- `condition1`,`condition2`,...:表达式的判断条件。 +- `result1`,`result2`,...:满足相应条件时要返回的值。 +- `result`:当没有条件满足时要返回的值(可选)。 + +## 示例 + +`CASE` 语句可以在各种子句中使用,例如 `SELECT`,`WHERE`,`ORDER BY` 和 `GROUP BY`。 + +### 在 `SELECT` 中使用 `CASE` + +在 `SELECT` 子句中,你可以使用 `CASE` 语句根据条件创建新列。 +请参阅查询数据指南中的[示例](/user-guide/query-data/sql.md#case)。 + +你还可以将 `CASE` 与 `SUM` 等函数一起使用,以有条件地聚合数据。 +例如,你可以计算状态码为 200 和 404 的日志总数: + +```sql +SELECT + SUM(CASE WHEN status_code = '200' THEN 1 ELSE 0 END) AS status_200_count, + SUM(CASE WHEN status_code = '404' THEN 1 ELSE 0 END) AS status_404_count +FROM nginx_logs; +``` + +### 在 `WHERE` 中使用 `CASE` + +在 `WHERE` 子句中,你可以根据条件过滤行。 +例如,以下查询根据 `ts` 条件从 `monitor` 表中检索数据: + +```sql +SELECT * +FROM monitor +WHERE host = CASE + WHEN ts > '2023-12-13 02:05:46' THEN '127.0.0.1' + ELSE '127.0.0.2' + END; +``` + +### 在 `GROUP BY` 中使用 `CASE` + +`CASE` 语句可以在 `GROUP BY` 子句中使用,以根据特定条件对数据进行分类。 +例如,以下查询按 `host` 列分组,并将 `cpu` 列分类为三类:'high','medium' 和 'low': + +```sql +SELECT + host, + COUNT(*) AS count, + CASE + WHEN cpu > 0.5 THEN 'high' + WHEN cpu > 0.3 THEN 'medium' + ELSE 'low' + END AS cpu_status +FROM monitor +GROUP BY + host, cpu_status; +``` + +### 在 `ORDER BY` 中使用 `CASE` + +根据 GreptimeDB 的[数据模型](/user-guide/concepts/data-model.md), +`Tag` 列拥有索引,可以在 `ORDER BY` 子句中使用以提高查询性能。 +假如 `nginx_logs` 表中的 `status_code` 和 `http_method` 列是存储字符串值的 `Tag` 列, +你可以利用 `CASE` 语句根据这些列对数据进行排序,如下所示: + +```sql +SELECT * +FROM nginx_logs +ORDER BY + CASE + WHEN status_code IS NOT NULL THEN status_code + ELSE http_method + END; +``` + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/cast.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/cast.md similarity index 69% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/cast.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/cast.md index 405aee98f..01f28fa47 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/cast.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/cast.md @@ -1,3 +1,8 @@ +--- +keywords: [数据类型转换, CAST 语句, SQL CAST, 类型转换, 数据类型, SQL 语法] +description: CAST 用于将一个数据类型的表达式转换为另一个数据类型。 +--- + # CAST `CAST` 用于将一个数据类型的表达式转换为另一个数据类型。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/compatibility.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/compatibility.md similarity index 63% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/compatibility.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/compatibility.md index 0f949e28d..a60bfcd39 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/compatibility.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/compatibility.md @@ -1,3 +1,8 @@ +--- +keywords: [ANSI SQL, SQL 兼容性, SQL 扩展, SQL 语法, 数据库兼容性, SQL 特性] +description: GreptimeDB 支持的 SQL 是 ANSI SQL 的子集,并且拥有一些特有的扩展。 +--- + # ANSI Compatibility GreptimeDB 支持的 SQL 是 ANSI SQL 的子集,并且拥有一些特有的扩展。一些主要的不兼容和扩展描述如下: @@ -8,10 +13,13 @@ GreptimeDB 支持的 SQL 是 ANSI SQL 的子集,并且拥有一些特有的扩 * GreptimeDB 是原生的分布式数据库,因此分布式表的建表语句支持分区规则,也请参考[CREATE](./create.md) 建表语法一节。 2. 插入新数据: 与 ANSI SQL 语法一致,但是强制要求提供 `TIME INDEX` 列值(或默认值)。 3. 更新:不支持 `UPDATE` 语法,但是在 `INSERT` 的时候,如果主键和 `TIME INDEX` 对应的列值一样,那么后续插入的行将覆盖以前写入的行,从而变相实现更新。 + * 从 0.8 开始, GreptimeDB 支持 [append 模式](/reference/sql/create.md#创建-Append-Only-表),创建时指定`append_mode = "true"` 选项的表将保留重复的数据行。 + * GreptimeDB 支持 [merge 模式](/reference/sql/create.md#create-an-append-only-table),该模式使用 `merge_mode="last_non_null"` 选项创建表,允许部分更新字段。 4. 查询:查询语法兼容 ANSI SQL,存在部分功能差异和缺失 - * 不支持视图 + * 从 v0.9.0 开始支持[视图](/user-guide/query-data/view.md)。 * TQL 语法扩展:TQL 子命令支持在 SQL 中执行 PromQL,详细请参考 [TQL](./tql.md) 一节。 + * [Range Query](/reference/sql/range.md#range-query) 支持按照指定窗口来查询和聚合时序数据。 5. 删除数据:语法与 ANSI SQL 基本一致。 6. 他项: * 标识符,如表名,列名等,约束与 ANSI SQL 类似,大小写敏感,遇到特殊字符或者大写需要用双引号括起来。 - * GreptimeDB 针对不同方言做了优化,比如用 MySQL 客户端或者 PostgreSQL 客户端连接到数据库时, 允许使用特定 SQL 方言的标识符规则,比如在 MySQL 中可以用反引号 ```,而在 PostgreSQL 中还是标准的双引号 `"`。 + * GreptimeDB 针对不同方言做了优化,比如用 MySQL 客户端或者 PostgreSQL 客户端连接到数据库时, 允许使用特定 SQL 方言的标识符规则,比如在 MySQL 中可以用反引号 `` ` ``,而在 PostgreSQL 中还是标准的双引号 `"`。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/copy.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/copy.md similarity index 92% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/copy.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/copy.md index 8b0770c99..d30f6f494 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/copy.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/copy.md @@ -1,3 +1,8 @@ +--- +keywords: [数据导入, 数据导出, COPY 语句, SQL COPY, 数据库复制, 表复制] +description: COPY 语句用于导入和导出表或数据库的数据。 +--- + # COPY ## COPY TABLE @@ -35,10 +40,11 @@ COPY [.] FROM { '/[]' } [ [ WITH ] ( - [ FORMAT = { parquet } ] + [ FORMAT = { 'CSV' | 'JSON' | 'PARQUET' | 'ORC' } ] [ PATTERN = '' ] ) ] +[LIMIT NUM] ``` 命令以 `COPY` 关键字开始,后面跟着要导入数据的表名。 @@ -61,13 +67,17 @@ COPY tbl FROM '/path/to/folder/xxx.parquet' WITH (FORMAT = 'parquet'); | 选项 | 描述 | 是否必需 | |---|---|---| -| `FORMAT` | 目标文件格式,例如 JSON, CSV, Parquet | **是** | +| `FORMAT` | 目标文件格式,例如 JSON, CSV, Parquet, ORC | **是** | | `PATTERN` | 使用正则匹配文件,例如 `*_today.parquet` | 可选 | #### Connection 选项 `COPY FROM` 同样支持从云存储上导入数据,比如 S3。详情请参考 [连接 S3](#连接-s3)。 +#### LIMIT 选项 + +可以通过 `LIMIT` 手动限制一次插入的最大行数。 + ### 连接 S3 你可以从 S3 导入/导出数据 @@ -119,7 +129,7 @@ https://bucket-name.s3.region-code.amazonaws.com/key-name COPY DATABASE [TO | FROM] '' WITH ( - FORMAT = "", + FORMAT = { 'CSV' | 'JSON' | 'PARQUET' } START_TIME = "", END_TIME = "" ) @@ -164,4 +174,4 @@ COPY tbl TO 'C:\xxx\xxx\output.parquet' WITH (FORMAT = 'parquet'); -- 下列语句能够正常执行 COPY tbl TO 'C:/xxx/xxx/output.parquet' WITH (FORMAT = 'parquet'); -``` \ No newline at end of file +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/create.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/create.md similarity index 56% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/create.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/create.md index a3cfa6867..7e907dadc 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/create.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/create.md @@ -1,3 +1,8 @@ +--- +keywords: [创建数据库, 创建表, CREATE 语句, SQL 创建, 数据库选项, 表选项] +description: CREATE 用于创建新的数据库或表,支持指定列、主键、时间索引、存储引擎和其他选项。 +--- + # CREATE `CREATE` 用于创建新的数据库或者表。 @@ -9,7 +14,7 @@ 创建新数据库: ```sql -CREATE DATABASE [IF NOT EXISTS] db_name +CREATE DATABASE [IF NOT EXISTS] db_name [WITH ] ``` 如果 `db_name` 数据库已经存在,`CREATE` 语句的行为如下: @@ -18,6 +23,8 @@ CREATE DATABASE [IF NOT EXISTS] db_name - 当 `IF NOT EXISTS` 子句被指定时,不会返回错误。 - 否则,返回错误。 +数据库也可以通过使用 `WITH` 关键字配置与 `CREATE TABLE` 语句类似的选项。[表选项](#表选项) 中提供的所有选项也可以在此处使用(一个例外是数据库的 TTL 不能为 `instant`)。在创建表时,如果未提供相应的表选项,将使用在数据库级别配置的选项或者默认值。 + ### 示例 创建名为 `test` 的数据库: @@ -36,6 +43,13 @@ Query OK, 1 row affected (0.05 sec) CREATE DATABASE IF NOT EXISTS test; ``` +创建一个具有 7 天 `TTL`(数据存活时间)的数据库,也就是该数据库中的所有表如果没有单独设置 TTL 选项,都将继承此选项值。 + +```sql +CREATE DATABASE test WITH (ttl='7d'); +``` + + ## CREATE TABLE ### Syntax @@ -45,12 +59,13 @@ CREATE DATABASE IF NOT EXISTS test; ```sql CREATE TABLE [IF NOT EXISTS] [db.]table_name ( - column1 type1 [NULL | NOT NULL] [DEFAULT expr1] [TIME INDEX] [PRIMARY KEY] [COMMENT comment1], - column2 type2 [NULL | NOT NULL] [DEFAULT expr2] [TIME INDEX] [PRIMARY KEY] [COMMENT comment2], + column1 type1 [NULL | NOT NULL] [DEFAULT expr1] [TIME INDEX] [PRIMARY KEY] [FULLTEXT | FULLTEXT WITH options] [COMMENT comment1], + column2 type2 [NULL | NOT NULL] [DEFAULT expr2] [TIME INDEX] [PRIMARY KEY] [FULLTEXT | FULLTEXT WITH options] [COMMENT comment2], ... [TIME INDEX (column)], - [PRIMARY KEY(column1, column2, ...)] -) ENGINE = engine WITH([TTL | REGIONS] = expr, ...) + [PRIMARY KEY(column1, column2, ...)], + [INVERTED INDEX(column1, column2, ...)] +) ENGINE = engine WITH([TTL | storage | ...] = expr, ...) [ PARTITION ON COLUMNS(column1, column2, ...) ( , @@ -78,39 +93,67 @@ CREATE TABLE [IF NOT EXISTS] [db.]table_name 如果表已经存在且创建表时指定了 `IF NOT EXISTS`,`CREATE` 语句不会返回错误;否则返回错误。 +#### 倒排索引 + +`INVERTED INDEX` 指定表的[倒排索引](/contributor-guide/datanode/data-persistence-indexing.md#倒排索引)列。倒排索引列可以是任何列。对于每一个指定的列,GreptimeDB 会创建倒排索引以加速查询。 + +- 如果没有指定 `INVERTED INDEX`,则为 `PRIMARY KEY` 中的列创建倒排索引。 +- 如果指定了 `INVERTED INDEX`,则仅为 `INVERTED INDEX` 中的列创建倒排索引。特别的,当指定为 `INVECTED INDEX()`,代表不会为任何列创建倒排索引。 + ### 表选项 用户可以使用 `WITH` 添加表选项。有效的选项包括以下内容: | 选项 | 描述 | 值 | | ------------------- | ---------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | -| `ttl` | 表数据的存储时间 | 字符串值,例如 `'60m'`, `'1h'` 代表 1 小时, `'14d'` 代表 14 天等。支持的时间单位有:`s` / `m` / `h` / `d` | -| `regions` | 表的 region 值 | 整数值,例如 1, 5, 10 etc. | -| `storage` | 自定义表的存储引擎,存储引擎提供商的名字 | 字符串,类似 `S3`、`Gcs` 等。 必须在 `[[storage.providers]]` 列表里配置, 参考 [configuration](/user-guide/operations/configuration.md#存储引擎提供商)。 | +| `ttl` | 表数据的存储时间 | 一个时间范围字符串,例如 `'60m'`, `'1h'` 代表 1 小时, `'14d'` 代表 14 天等。支持的时间单位有:`s` / `m` / `h` / `d`| +| `storage` | 自定义表的存储引擎,存储引擎提供商的名字 | 字符串,类似 `S3`、`Gcs` 等。 必须在 `[[storage.providers]]` 列表里配置, 参考 [configuration](/user-guide/deployments/configuration.md#存储引擎提供商)。 | | `compaction.type` | Compaction 策略 | 字符串值. 只支持 `twcs`。你可以阅读这篇[文章](https://cassandra.apache.org/doc/latest/cassandra/managing/operating/compaction/twcs.html)来了解 `twcs` compaction 策略 | | `compaction.twcs.max_active_window_files` | 当前活跃时间窗口内的最大文件数 | 字符串值,如 '8'。只在 `compaction.type` 为 `twcs` 时可用 | | `compaction.twcs.max_inactive_window_files` | 非活跃时间窗口内的最大文件数 | 字符串值,如 '1'。只在 `compaction.type` 为 `twcs` 时可用 | | `compaction.twcs.time_window` | Compaction 时间窗口 | 字符串值,如 '1d' 表示 1 天。该表会根据时间戳将数据分区到不同的时间窗口中。只在 `compaction.type` 为 `twcs` 时可用 | | `memtable.type` | memtable 的类型 | 字符串值,支持 `time_series`,`partition_tree` | +| `append_mode` | 该表是否时 append-only 的 | 字符串值。默认值为 'false',根据 'merge_mode' 按主键和时间戳删除重复行。设置为 'true' 可以开启 append 模式和创建 append-only 表,保留所有重复的行 | +| `merge_mode` | 合并重复行的策略 | 字符串值。只有当 `append_mode` 为 'false' 时可用。默认值为 `last_row`,保留相同主键和时间戳的最后一行。设置为 `last_non_null` 则保留相同主键和时间戳的最后一个非空字段。 | +| `comment` | 表级注释 | 字符串值. | -例如,创建一个存储数据 TTL(Time-To-Live) 为七天,region 数为 10 的表: +#### 创建指定 TTL 的表 +例如,创建一个存储数据 TTL(Time-To-Live) 为七天的表: ```sql CREATE TABLE IF NOT EXISTS temperatures( ts TIMESTAMP TIME INDEX, temperature DOUBLE DEFAULT 10, -) engine=mito with(ttl='7d', regions=10); +) with(ttl='7d'); +``` +`ttl` 值是一个字符串,支持以下类型的值: + +- [时间范围字符串](/reference/time-durations.md),如 `1hour 12min 5s`。 +- `forever`, `NULL`, `0s` (或任何长度为 0 的时间范围,如 `0d`)或空字符串 `''`,表示数据永远不会被删除。 +- `instant`, 注意数据库的 TTL 不能设置为 `instant`。`instant` 表示数据在插入时立即删除,如果你想将输入发送到流任务而不保存它,可以使用 `instant`,请参阅[流管理文档](/user-guide/flow-computation/manage-flow.md#manage-flows)了解更多细节。 +- 未设置,可以使用 `ALTER TABLE UNSET 'ttl'` 来取消表的 `ttl` 设置,这样表将继承数据库的 `ttl` 策略(如果有的话)。 + +如果一张表有自己的 TTL 策略,那么它将使用该 TTL 策略。否则,数据库的 TTL 策略将被应用到表上。 + +比如说,如果表的 TTL 设置为 `forever`,那么无论数据库的 TTL 是什么,数据都不会被删除。但是如果你取消表的 TTL 设置: +```sql +ALTER TABLE UNSET 'ttl'; ``` +那么数据库的 TTL 将会被应用到表上。 +请注意表和数据库的默认 TTL 策略都是未设置,也就是没有设置 TTL,代表着数据永远不会删除。 + +#### 创建自定义存储的表 或者创建一个表单独将数据存储在 Google Cloud Storage 服务上: ```sql CREATE TABLE IF NOT EXISTS temperatures( ts TIMESTAMP TIME INDEX, temperature DOUBLE DEFAULT 10, -) engine=mito with(ttl='7d', regions=10, storage="Gcs"); +) with(ttl='7d', storage="Gcs"); ``` +#### 创建自定义 compaction 参数的表 创建带自定义 twcs compaction 参数的表。这个表会尝试根据数据的时间戳将数据按 1 天的时间窗口分区。 - 它会在最新时间窗口内的文件超过 8 个时合并该窗口的文件 - 它会将非最新窗口内的文件合并为一个文件 @@ -120,7 +163,6 @@ CREATE TABLE IF NOT EXISTS temperatures( ts TIMESTAMP TIME INDEX, temperature DOUBLE DEFAULT 10, ) -engine=mito with( 'compaction.type'='twcs', 'compaction.twcs.time_window'='1d', @@ -129,6 +171,77 @@ with( ); ``` +#### 创建 Append-Only 表 +创建一个 append-only 表来关闭去重 +```sql +CREATE TABLE IF NOT EXISTS temperatures( + ts TIMESTAMP TIME INDEX, + temperature DOUBLE DEFAULT 10, +) with('append_mode'='true'); +``` + +#### 创建带有 merge 模式的表 + +创建一个带有 `last_row` merge 模式的表,这是默认的 merge 模式。 + +```sql +create table if not exists metrics( + host string, + ts timestamp, + cpu double, + memory double, + TIME INDEX (ts), + PRIMARY KEY(host) +) +with('merge_mode'='last_row'); +``` + +在 `last_row` 模式下,表会通过保留最新的行来合并具有相同主键和时间戳的行。 + +```sql +INSERT INTO metrics VALUES ('host1', 0, 0, NULL), ('host2', 1, NULL, 1); +INSERT INTO metrics VALUES ('host1', 0, NULL, 10), ('host2', 1, 11, NULL); + +SELECT * from metrics ORDER BY host, ts; + ++-------+-------------------------+------+--------+ +| host | ts | cpu | memory | ++-------+-------------------------+------+--------+ +| host1 | 1970-01-01T00:00:00 | | 10.0 | +| host2 | 1970-01-01T00:00:00.001 | 11.0 | | ++-------+-------------------------+------+--------+ +``` + + +创建带有 `last_non_null` merge 模式的表。 + +```sql +create table if not exists metrics( + host string, + ts timestamp, + cpu double, + memory double, + TIME INDEX (ts), + PRIMARY KEY(host) +) +with('merge_mode'='last_non_null'); +``` + +在 `last_non_null` 模式下,表会通过保留每个字段的最新值来合并具有相同主键和时间戳的行。 + +```sql +INSERT INTO metrics VALUES ('host1', 0, 0, NULL), ('host2', 1, NULL, 1); +INSERT INTO metrics VALUES ('host1', 0, NULL, 10), ('host2', 1, 11, NULL); + +SELECT * from metrics ORDER BY host, ts; + ++-------+-------------------------+------+--------+ +| host | ts | cpu | memory | ++-------+-------------------------+------+--------+ +| host1 | 1970-01-01T00:00:00 | 0.0 | 10.0 | +| host2 | 1970-01-01T00:00:00.001 | 11.0 | 1.0 | ++-------+-------------------------+------+--------+ +``` ### 列选项 @@ -140,6 +253,7 @@ GreptimeDB 支持以下列选项: | NOT NULL | 列值不能为 `null` | | DEFAULT `expr` | 该列的默认值是 `expr`,其类型必须是该列的类型 | | COMMENT `comment` | 列注释,必须为字符串类型 | +| FULLTEXT | 创建全文索引,可以加速全文搜索操作。仅适用于字符串类型列 | 表约束 `TIME INDEX` 和 `PRIMARY KEY` 也可以通过列选项设置,但是它们只能在列定义中指定一次,在多个列选项中指定 `PRIMARY KEY` 会报错: @@ -179,6 +293,32 @@ CREATE TABLE system_metrics ( Query OK, 0 rows affected (0.01 sec) ``` +#### `FULLTEXT` 列选项 + +`FULLTEXT` 用于创建全文索引,加速全文搜索操作。该选项只能应用于字符串类型的列。 + +使用 `FULLTEXT WITH` 可以指定以下选项: + +- `analyzer`:设置全文索引的分析器语言,支持 `English` 和 `Chinese`。 +- `case_sensitive`:设置全文索引是否区分大小写,支持 `true` 和 `false`。 + +如果不带 `WITH` 选项,`FULLTEXT` 将使用默认值: + +- `analyzer`:默认 `English` +- `case_sensitive`:默认 `false` + +例如,要创建一个带有全文索引的表,配置 `log` 列为全文索引,并指定分析器为 `Chinese` 且不区分大小写: + +```sql +CREATE TABLE IF NOT EXISTS logs( + host STRING PRIMARY KEY, + log STRING FULLTEXT WITH(analyzer = 'Chinese', case_sensitive = 'false'), + ts TIMESTAMP TIME INDEX +); +``` + +更多关于全文索引和全文搜索的使用,请参阅 [日志查询文档](/user-guide/logs/query-logs.md)。 + ### Region 分区规则 请参考 [分区](/contributor-guide/frontend/table-sharding.md#partition) 章节. @@ -207,7 +347,7 @@ CREATE EXTERNAL TABLE [IF NOT EXISTS] [db.]table_name [,ENDPOINT = uri ] [,ACCESS_KEY_ID = key_id ] [,SECRET_ACCESS_KEY = access_key ] - [,ENABLE_VIRTUAL_HOST_STYLE = { TRUE | FALSE }] + [,ENABLE_VIRTUAL HOST_STYLE = { TRUE | FALSE }] [,SESSION_TOKEN = token ] ... ) @@ -229,7 +369,7 @@ CREATE EXTERNAL TABLE [IF NOT EXISTS] [db.]table_name | `ENDPOINT` | The bucket endpoint | 可选 | | `ACCESS_KEY_ID` | 用于连接 AWS S3 兼容对象存储的访问密钥 ID | 可选 | | `SECRET_ACCESS_KEY` | 用于连接 AWS S3 兼容对象存储的秘密访问密钥 | 可选 | -| `ENABLE_VIRTUAL_HOST_STYLE` | 如果你想要使用 virtual hosting 来定位 bucket,将其设置为 `true` | 可选 | +| `ENABLE_VIRTUAL HOST_STYLE` | 如果你想要使用 virtual hosting 来定位 bucket,将其设置为 `true` | 可选 | | `SESSION_TOKEN` | 用于连接 AWS S3 服务的临时凭证 | 可选 | ### 时间索引列 @@ -264,3 +404,25 @@ CREATE EXTERNAL TABLE city ( ``` 在这个例子中,我们明确定义了 `ts` 列作为时间索引列。如果在文件中没有适合的时间索引列,你也可以创建一个占位符列,并添加 `DEFAULT expr` 约束。 + +## 创建 Flow + +```sql +CREATE [OR REPLACE] FLOW [ IF NOT EXISTS ] +SINK TO +[ EXPIRE AFTER ] +[ COMMENT '' ] +AS +; +``` + +用于创建或更新 Flow 任务,请阅读[Flow 管理文档](/user-guide/flow-computation/manage-flow.md#创建-flow)。 + +## 创建 View + +```sql +CREATE [OR REPLACE] VIEW [ IF NOT EXISTS ] +AS select_statement +``` + +用于创建或更新视图,请阅读[视图用户指南](/user-guide/query-data/view.md#视图)。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/data-types.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/data-types.md new file mode 100644 index 000000000..91b6a396b --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/data-types.md @@ -0,0 +1,378 @@ +--- +keywords: [SQL 数据类型, 字符串类型, 数值类型, 日期和时间类型, 布尔类型, JSON 类型] +description: SQL 数据类型定义了列可以存储的数据类型,包括字符串、二进制、数值、日期和时间、布尔和 JSON 类型。 +--- + +# 数据类型 + +SQL 数据类型定义了列可以存储的数据类型。当您运行 `DESC TABLE` 命令时,你可以看到每列的数据类型。 + +## 字符串和二进制数据类型 + +| 类型名称 | 描述 | 大小 | +|-----------|-------------|------| +| `String` | UTF-8 编码的字符串。最多可容纳 2,147,483,647 字节的数据 | 字符串的长度 | +| `Binary` | 变长二进制值。最多可容纳 2,147,483,647 字节的数据 | 数据的长度 + 2 字节 | + +`String` 和 `Binary` 的最大容量取决于它们的编码方式以及存储引擎如何处理它们。例如,`String` 值被编码为 UTF-8,如果所有字符的长度为 3 个字节,该字段最多可以存储 715,827,882 个字符。对于 `Binary` 类型,它们最多可以存储 2,147,483,647 字节。 + +## 数值数据类型 + +| 类型名称 | 描述 | 大小 | +|-----------|-------------|------| +| `Int8` | -128 ~ 127 | 1 字节 | +| `Int16` | -32768 ~ 32767 | 2 字节 | +| `Int32` | -2147483648 ~ 2147483647 | 4 字节 | +| `Int64` | -9223372036854775808 ~ 9223372036854775807 | 8 字节 | +| `UInt8` | 0 ~ 255 | 1 字节 | +| `UInt16` | 0 ~ 65535 | 2 字节 | +| `UInt32` | 0 ~ 4294967295 | 4 字节 | +| `UInt64` | 0 ~ 18446744073709551615 | 8 字节 | +| `Float32` | 32 位 IEEE 754 浮点数 | 4 字节 | +| `Float64` | 双精度 IEEE 754 浮点数 | 8 字节 | + +## Decimal 类型 + +GreptimeDB 支持 `decimal` 类型,这是一种定点类型,表示为 `decimal(precision, scale)`,其中 `precision` 是总位数,`scale` 是小数部分的位数。例如,`123.45` 的总位数为 5,小数位数为 2。 + +- `precision` 可以在 [1, 38] 范围内。 +- `scale` 可以在 [0, precision] 范围内。 + +如果未指定总位数和比例,则默认的十进制数是 `decimal(38, 10)`。 + +```sql +CREATE TABLE decimals( + d DECIMAL(3, 2), + ts TIMESTAMP TIME INDEX, +); + +INSERT INTO decimals VALUES ('0.1',1000), ('0.2',2000); + +SELECT * FROM decimals; +``` + +```sql ++------+---------------------+ +| d | ts | ++------+---------------------+ +| 0.10 | 1970-01-01T00:00:01 | +| 0.20 | 1970-01-01T00:00:02 | ++------+---------------------+ +``` + +## 日期和时间类型 + +| 类型名称 | 描述 | 大小 | +|-----------|-------------|------| +| `TimestampSecond` | 64 位时间戳值,精度为秒,范围:`[-262144-01-01 00:00:00, +262143-12-31 23:59:59]` | 8 字节 | +| `TimestampMillisecond` | 64 位时间戳值,毫秒精度,范围:`[-262144-01-01 00:00:00.000, +262143-12-31 23:59:59.999]` | 8 字节 | +| `TimestampMicroSecond` | 64 位时间戳值,微秒精度,范围:`[-262144-01-01 00:00:00.000000, +262143-12-31 23:59:59.999999]` | 8 字节 | +| `TimestampNanosecond` | 64 位时间戳值,纳秒精度,范围: `[1677-09-21 00:12:43.145225, 2262-04-11 23:47:16.854775807]` | 8 字节 | +| `Interval`| 时间间隔 | 对于 `YearMonth`, 使用4字节,对于 `DayTime`, 使用8字节,对于 `MonthDayNano`, 使用16字节 | + +:::tip 注意 +使用 MySQL/PostgreSQL 协议写入时间戳字符串字面量时,值的范围限制为 '0001-01-01 00:00:00' 到 '9999-12-31 23:59:59'。 +::: + +### Interval 类型详解 + +`Interval` 类型用于需要跟踪和操作时间间隔的场景。它的编写语法如下: + +``` +QUANTITY UNIT [QUANTITY UNIT...] +``` + +* `QUANTITY`:是一个数字(可能有符号), +* `UNIT`:时间单位,可以是 `microsecond`(微秒)、`millisecond`(毫秒)、`second`(秒)、`minute`(分钟)、`hour`(小时)、`day`(天)、`week`(周)、`month`(月)、`year`(年)、`decade`(十年)、`century`(世纪)或这些单位的缩写或复数形式; + +不同的时间单位将会被计算合并,每个单位的符号决定它是增加还是减少总间隔。例如,“1 年 -2 个月”导致净间隔为 10 个月。 +遗憾的是,GreptimeDB 暂时还不支持以 [ISO 8601 时间间隔](https://en.wikipedia.org/wiki/ISO_8601#Time_intervals)格式编写间隔,例如 `P3Y3M700DT133H17M36.789S` 等。但它支持以这种格式输出。 + +让我们来看一些例子: + +```sql +SELECT '2 years 15 months 100 weeks 99 hours 123456789 milliseconds'::INTERVAL; +``` + +```sql ++---------------------------------------------------------------------+ +| Utf8("2 years 15 months 100 weeks 99 hours 123456789 milliseconds") | ++---------------------------------------------------------------------+ +| P3Y3M700DT133H17M36.789S | ++---------------------------------------------------------------------+ +``` + +55 分钟前: + +```sql +SELECT '-1 hour 5 minute'::INTERVAL; +``` + +```sql ++--------------------------+ +| Utf8("-1 hour 5 minute") | ++--------------------------+ +| P0Y0M0DT0H-55M0S | ++--------------------------+ +``` + +1 小时 5 分钟前: + +```sql +SELECT '-1 hour -5 minute'::INTERVAL; +``` + +```sql ++---------------------------+ +| Utf8("-1 hour -5 minute") | ++---------------------------+ +| P0Y0M0DT-1H-5M0S | ++---------------------------+ +``` + +当然,你可以通过算术运算来操作时间间隔。 +获取 5 分钟前的时间: + +```sql +SELECT now() - INTERVAL '5 minute'; +``` + +```sql ++----------------------------------------------+ +| now() - IntervalMonthDayNano("300000000000") | ++----------------------------------------------+ +| 2024-06-24 21:24:05.012306 | ++----------------------------------------------+ +``` + +注意到你也可以用 `INTERVAL 'literal'` 的方式来输入 interval 类型。`'-1 hour -5 minute'::INTERVAL` 这样的方式其实是一个`CAST` 函数调用。 + +GreptimeDB 还支持类似 `3y2mon4h` 这样不包含空格的简写形式: + +```sql +SELECT INTERVAL '3y2mon4h'; +SELECT '3y2mon4h'::INTERVAL; +``` + +``` ++---------------------------------------------------------+ +| IntervalMonthDayNano("3010670175542044842954670112768") | ++---------------------------------------------------------+ +| P3Y2M0DT4H0M0S | ++---------------------------------------------------------+ ++---------------------------------------------------------+ +| IntervalMonthDayNano("3010670175542044842954670112768") | ++---------------------------------------------------------+ +| P3Y2M0DT4H0M0S | ++---------------------------------------------------------+ +``` + +同样也支持符号数: + +```sql +SELECT INTERVAL '-1h5m'; +SELECT '-1h5m'::INTERVAL; +``` + +``` ++----------------------------------------------+ +| IntervalMonthDayNano("18446740773709551616") | ++----------------------------------------------+ +| P0Y0M0DT0H-55M0S | ++----------------------------------------------+ ++----------------------------------------------+ +| IntervalMonthDayNano("18446740773709551616") | ++----------------------------------------------+ +| P0Y0M0DT0H-55M0S | ++----------------------------------------------+ +``` + +支持的缩写包括: + +| 缩写 | 全称 | +|-------|---------------| +| y | years | +| mon | months | +| w | weeks | +| d | days | +| h | hours | +| m | minutes | +| s | seconds | +| millis| milliseconds | +| ms | milliseconds | +| us | microseconds | +| ns | nanoseconds | + +## JSON 类型 +GreptimeDB 支持 JSON 类型,允许用户存储和查询 JSON 格式的数据。JSON 类型非常灵活,可以存储各种形式的结构化或非结构化数据,适合日志记录、分析和半结构化数据存储等场景。 + +```sql +CREATE TABLE json_data( + my_json JSON, + ts TIMESTAMP TIME INDEX +); + +INSERT INTO json_data VALUES ('{"key1": "value1", "key2": 10}', 1000), + ('{"name": "GreptimeDB", "open_source": true}', 2000); + +SELECT * FROM json_data; +``` + +输出: + +``` ++------------------------------------------+---------------------+ +| my_json | ts | ++------------------------------------------+---------------------+ +| {"key1":"value1","key2":10} | 1970-01-01 00:00:01 | +| {"name":"GreptimeDB","open_source":true} | 1970-01-01 00:00:02 | ++------------------------------------------+---------------------+ +``` + +### 查询 JSON 数据 + +您可以直接查询 JSON 数据,也可以使用 GreptimeDB 提供的 [JSON 函数](./functions/overview.md#json-functions) 提取特定字段。以下是一个示例: + +```sql +SELECT json_get_string(my_json, '$.name') as name FROM json_data; +``` + +输出: + +``` ++---------------------------------------------------+ +| name | ++---------------------------------------------------+ +| NULL | +| GreptimeDB | ++---------------------------------------------------+ +``` + + +## 布尔类型 + +| 类型名称 | 描述 | 大小 | +|-----------|-------------|------| +| `Boolean` | 布尔值 | 1 字节 | + +在 SQL 语句中使用 `TRUE` 或 `FALSE` 表示布尔值。例如: + +```sql +CREATE TABLE bools( + b BOOLEAN, + ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP() TIME INDEX, +); +``` + +```sql +INSERT INTO bools(b) VALUES (TRUE), (FALSE); +``` + +## 与 MySQL 和 PostgreSQL 兼容的数据类型 + +### 类型别名 + +对于从 MySQL 或 PostgreSQL 迁移到 GreptimeDB 的用户,GreptimeDB 支持以下类型别名。 + +| 数据类型 | 别名 | +| ---------------------- | --------------------------------------------------------------- | +| `String` | `Text`, `TinyText`, `MediumText`, `LongText`, `Varchar`, `Char` | +| `Binary` | `Varbinary` | +| `Int8` | `TinyInt` | +| `Int16` | `SmallInt` | +| `Int32` | `Int` | +| `Int64` | `BigInt` | +| `UInt8` | `UnsignedTinyInt` | +| `UInt16` | `UnsignedSmallInt` | +| `UInt32` | `UnsignedInt` | +| `UInt64` | `UnsignedBigInt` | +| `Float32` | `Float` | +| `Float64` | `Double` | +| `TimestampSecond` | `Timestamp_s`, `Timestamp_sec`, `Timestamp(0)` | +| `TimestampMillisecond` | `Timestamp`, `Timestamp_ms` , `Timestamp(3)` | +| `TimestampMicroSecond` | `Timestamp_us`, `Timestamp(6)` | +| `TimestampNanosecond` | `Timestamp_ns`, `Timestamp(9)` | + +在创建表时也可以使用这些别名类型。 +例如,使用 `Varchar` 代替 `String`,使用 `Double` 代替 `Float64`,使用 `Timestamp(0)` 代替 `TimestampSecond`。 + +```sql +CREATE TABLE alias_types ( + s TEXT, + i Double, + ts0 Timestamp(0) DEFAULT CURRENT_TIMESTAMP() TIME INDEX, + PRIMARY KEY(s) +); +``` + +### 日期和时间类型 + +除了在 GreptimeDB 中用作默认时间类型的 `Timestamp` 类型之外 +GreptimeDB 还支持与 MySQL 和 PostgreSQL 兼容的 `Date` 和 `DateTime` 类型。 + +| 类型名称 | 描述 | 大小 | +|-----------|-------------|------| +|`Date` |32 位日期值,表示自 UNIX Epoch 以来的天数 | 4 字节 | +|`DateTime` |64 位日期时间值,表示自 UNIX Epoch 以来的毫秒数| 8 字节 | + +## 示例 + +### 创建表 + +```sql +CREATE TABLE data_types ( + s STRING, + vbi BINARY, + b BOOLEAN, + tint INT8, + sint INT16, + i INT32, + bint INT64, + utint UINT8, + usint UINT16, + ui UINT32, + ubint UINT64, + f FLOAT32, + d FLOAT64, + dm DECIMAL(3, 2), + dt DATE, + dtt DATETIME, + ts0 TIMESTAMPSECOND, + ts3 TIMESTAMPMILLISECOND, + ts6 TIMESTAMPMICROSECOND, + ts9 TIMESTAMPNANOSECOND DEFAULT CURRENT_TIMESTAMP() TIME INDEX, + PRIMARY KEY(s)); +``` + +### 描述表结构 + +```sh +DESC TABLE data_types; +``` + +```sql ++--------+----------------------+------+------+---------------------+---------------+ +| Column | Type | Key | Null | Default | Semantic Type | ++--------+----------------------+------+------+---------------------+---------------+ +| s | String | PRI | YES | | TAG | +| vbi | Binary | | YES | | FIELD | +| b | Boolean | | YES | | FIELD | +| tint | Int8 | | YES | | FIELD | +| sint | Int16 | | YES | | FIELD | +| i | Int32 | | YES | | FIELD | +| bint | Int64 | | YES | | FIELD | +| utint | UInt8 | | YES | | FIELD | +| usint | UInt16 | | YES | | FIELD | +| ui | UInt32 | | YES | | FIELD | +| ubint | UInt64 | | YES | | FIELD | +| f | Float32 | | YES | | FIELD | +| d | Float64 | | YES | | FIELD | +| dm | Decimal(3, 2) | | YES | | FIELD | +| dt | Date | | YES | | FIELD | +| dtt | DateTime | | YES | | FIELD | +| ts0 | TimestampSecond | | YES | | FIELD | +| ts3 | TimestampMillisecond | | YES | | FIELD | +| ts6 | TimestampMicrosecond | | YES | | FIELD | +| ts9 | TimestampNanosecond | PRI | NO | current_timestamp() | TIMESTAMP | ++--------+----------------------+------+------+---------------------+---------------+ +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/delete.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/delete.md similarity index 72% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/delete.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/delete.md index f2d1e1e20..4d78aa4a5 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/delete.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/delete.md @@ -1,3 +1,8 @@ +--- +keywords: [SQL DELETE 语句, 删除行数据, 数据删除, SQL 示例, 数据库操作] +description: DELETE 用于从表中删除行数据,满足条件的行会立刻被标记,后续查询无法获取这些行数据。 +--- + # DELETE `DELETE` 用于从表中删除行数据。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/describe_table.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/describe_table.md similarity index 83% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/describe_table.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/describe_table.md index 53d044c81..5a129f5a6 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/describe_table.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/describe_table.md @@ -1,3 +1,8 @@ +--- +keywords: [SQL DESCRIBE TABLE 语句, 表结构描述, 列信息, 数据库表, SQL 示例] +description: DESCRIBE TABLE 用于描述数据库中表的结构,包括列名、类型、主键、是否为空、默认值和语义类型。 +--- + # DESCRIBE TABLE `DESCRIBE [TABLE] [db.]table` 描述了 `db` 或当前使用的数据库中的表结构。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/distinct.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/distinct.md similarity index 75% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/distinct.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/distinct.md index 1d7a64783..a5f7afea9 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/distinct.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/distinct.md @@ -1,3 +1,8 @@ +--- +keywords: [SQL DISTINCT 语句, 唯一值选择, 数据去重, SQL 示例, 数据分析] +description: SELECT DISTINCT 用于从一组数据中选择唯一值,可以与过滤条件结合使用。 +--- + # DISTINCT `SELECT DISTINCT` 用于从一组数据中选择唯一值,从查询的输出中返回唯一值,其基本语法如下: diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/drop.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/drop.md new file mode 100644 index 000000000..c4fd9f96f --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/drop.md @@ -0,0 +1,94 @@ +--- +keywords: [SQL DROP 语句, 删除数据库, 删除表, 删除视图, 删除流, SQL 示例] +description: DROP 用于删除数据库、表、流或视图,操作不可撤销,需谨慎使用。 +--- + +# DROP + +## DROP DATABASE + +`DROP DATABASE` 用于删除数据库,它删除数据库的目录项并删除包含数据的目录。 + +:::danger 危险操作 + +`DROP DATABASE` 无法撤消。请谨慎使用! + +::: + +### 语法 + +```sql +DROP DATABASE [ IF EXISTS ] db_name +``` + +- `IF EXISTS`: 如果数据库不存在,则不抛出错误。 +- `db_name`: 要删除的数据库的名称。 + +### 示例 + +删除名为 `test` 的数据库: + +```sql +DROP DATABASE test; +``` + +## DROP TABLE + +`DROP TABLE` 从数据库中删除表,它将删除该表的表定义和所有表数据、索引、规则和约束。 + +:::danger 危险操作 + +`DROP TABLE` 无法撤消。请谨慎使用! + +::: + +### 语法 + +```sql +DROP TABLE [ IF EXISTS ] table_name +``` + +- `IF EXISTS`: 如果表不存在,则不抛出错误。 +- `table_name`: 要删除的表的名称。 + +### 示例 + +删除 `monitor` 表: + +```sql +DROP TABLE monitor; +``` + +## 删除 Flow + +```sql +DROP FLOW [ IF EXISTS ] flow_name; +``` + +- `IF EXISTS`: 如果流不存在,则不抛出错误。 +- `flow_name`: 要删除的流的名称。 + +```sql +DROP FLOW IF EXISTS test_flow; +``` + +``` +Query OK, 0 rows affected (0.00 sec) +``` + +## 删除 View + +```sql +DROP VIEW [ IF EXISTS ] view_name; +``` + +- `IF EXISTS`: 如果视图不存在,则不抛出错误。 +- `view_name`: 要删除的视图的名称。 + +```sql +DROP VIEW IF EXISTS test_view; +``` + +``` +Query OK, 0 rows affected (0.00 sec) +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/explain.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/explain.md similarity index 91% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/explain.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/explain.md index 8ae708d30..b549366f8 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/explain.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/explain.md @@ -1,3 +1,8 @@ +--- +keywords: [SQL EXPLAIN 语句, 执行计划, 查询优化, ANALYZE 子句, SQL 示例] +description: EXPLAIN 用于提供语句的执行计划,ANALYZE 子句将执行语句并测量每个计划节点的时间和输出行数。 +--- + # EXPLAIN `EXPLAIN` 用于提供语句的执行计划。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/functions/df-functions.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/functions/df-functions.md new file mode 100644 index 000000000..7f0ad05c5 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/functions/df-functions.md @@ -0,0 +1,5037 @@ +--- +keywords: [DataFusion functions, scalar functions, window functions, array functions] +description: 介绍了 Apache DataFusion 项目中的函数,包括标量函数和窗口函数的定义、使用方法和相关的 SQL 查询示例。 +--- + +# DataFusion Functions + +This page is generated from the Apache DataFusion project's documents: + * [DataFusion Scalar Functions](https://raw.githubusercontent.com/apache/datafusion/main/docs/source/user-guide/sql/scalar_functions.md) + * [DataFusion Scalar Functions (NEW)](https://raw.githubusercontent.com/apache/datafusion/main/docs/source/user-guide/sql/scalar_functions_new.md) + * [DataFusion Aggregate Functions](https://raw.githubusercontent.com/apache/datafusion/main/docs/source/user-guide/sql/aggregate_functions.md) + * [DataFusion Window Functions](https://raw.githubusercontent.com/apache/datafusion/main/docs/source/user-guide/sql/window_functions.md) + + + +## Scalar Functions + +Scalar functions operate on a single row at a time and return a single value. + +Note: this documentation is in the process of being migrated to be [automatically created from the codebase]. +Please see the [Scalar Functions (new)](#scalar-functions-new) page for +the rest of the documentation. + +### Math Functions + +- [abs](#abs) +- [acos](#acos) +- [acosh](#acosh) +- [asin](#asin) +- [asinh](#asinh) +- [atan](#atan) +- [atanh](#atanh) +- [atan2](#atan2) +- [cbrt](#cbrt) +- [ceil](#ceil) +- [cos](#cos) +- [cosh](#cosh) +- [degrees](#degrees) +- [exp](#exp) +- [factorial](#factorial) +- [floor](#floor) +- [gcd](#gcd) +- [isnan](#isnan) +- [iszero](#iszero) +- [lcm](#lcm) +- [ln](#ln) +- [log10](#log10) +- [log2](#log2) +- [nanvl](#nanvl) +- [pi](#pi) +- [power](#power) +- [pow](#pow) +- [radians](#radians) +- [random](#random) +- [round](#round) +- [signum](#signum) +- [sin](#sin) +- [sinh](#sinh) +- [sqrt](#sqrt) +- [tan](#tan) +- [tanh](#tanh) +- [trunc](#trunc) + +##### `abs` + +Returns the absolute value of a number. + +``` +abs(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. + Can be a constant, column, or function, and any combination of arithmetic operators. + +##### `acos` + +Returns the arc cosine or inverse cosine of a number. + +``` +acos(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. + Can be a constant, column, or function, and any combination of arithmetic operators. + +##### `acosh` + +Returns the area hyperbolic cosine or inverse hyperbolic cosine of a number. + +``` +acosh(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. + Can be a constant, column, or function, and any combination of arithmetic operators. + +##### `asin` + +Returns the arc sine or inverse sine of a number. + +``` +asin(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. + Can be a constant, column, or function, and any combination of arithmetic operators. + +##### `asinh` + +Returns the area hyperbolic sine or inverse hyperbolic sine of a number. + +``` +asinh(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. + Can be a constant, column, or function, and any combination of arithmetic operators. + +##### `atan` + +Returns the arc tangent or inverse tangent of a number. + +``` +atan(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. + Can be a constant, column, or function, and any combination of arithmetic operators. + +##### `atanh` + +Returns the area hyperbolic tangent or inverse hyperbolic tangent of a number. + +``` +atanh(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. + Can be a constant, column, or function, and any combination of arithmetic operators. + +##### `atan2` + +Returns the arc tangent or inverse tangent of `expression_y / expression_x`. + +``` +atan2(expression_y, expression_x) +``` + +###### Arguments + +- **expression_y**: First numeric expression to operate on. + Can be a constant, column, or function, and any combination of arithmetic operators. +- **expression_x**: Second numeric expression to operate on. + Can be a constant, column, or function, and any combination of arithmetic operators. + +##### `cbrt` + +Returns the cube root of a number. + +``` +cbrt(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. + Can be a constant, column, or function, and any combination of arithmetic operators. + +##### `ceil` + +Returns the nearest integer greater than or equal to a number. + +``` +ceil(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. + Can be a constant, column, or function, and any combination of arithmetic operators. + +##### `cos` + +Returns the cosine of a number. + +``` +cos(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. + Can be a constant, column, or function, and any combination of arithmetic operators. + +##### `cosh` + +Returns the hyperbolic cosine of a number. + +``` +cosh(numeric_expression) +``` + +##### `degrees` + +Converts radians to degrees. + +``` +degrees(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. + Can be a constant, column, or function, and any combination of arithmetic operators. + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. + Can be a constant, column, or function, and any combination of arithmetic operators. + +##### `exp` + +Returns the base-e exponential of a number. + +``` +exp(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to use as the exponent. + Can be a constant, column, or function, and any combination of arithmetic operators. + +##### `factorial` + +Factorial. Returns 1 if value is less than 2. + +``` +factorial(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. + Can be a constant, column, or function, and any combination of arithmetic operators. + +##### `floor` + +Returns the nearest integer less than or equal to a number. + +``` +floor(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. + Can be a constant, column, or function, and any combination of arithmetic operators. + +##### `gcd` + +Returns the greatest common divisor of `expression_x` and `expression_y`. Returns 0 if both inputs are zero. + +``` +gcd(expression_x, expression_y) +``` + +###### Arguments + +- **expression_x**: First numeric expression to operate on. + Can be a constant, column, or function, and any combination of arithmetic operators. +- **expression_y**: Second numeric expression to operate on. + Can be a constant, column, or function, and any combination of arithmetic operators. + +##### `isnan` + +Returns true if a given number is +NaN or -NaN otherwise returns false. + +``` +isnan(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. + Can be a constant, column, or function, and any combination of arithmetic operators. + +##### `iszero` + +Returns true if a given number is +0.0 or -0.0 otherwise returns false. + +``` +iszero(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. + Can be a constant, column, or function, and any combination of arithmetic operators. + +##### `lcm` + +Returns the least common multiple of `expression_x` and `expression_y`. Returns 0 if either input is zero. + +``` +lcm(expression_x, expression_y) +``` + +###### Arguments + +- **expression_x**: First numeric expression to operate on. + Can be a constant, column, or function, and any combination of arithmetic operators. +- **expression_y**: Second numeric expression to operate on. + Can be a constant, column, or function, and any combination of arithmetic operators. + +##### `ln` + +Returns the natural logarithm of a number. + +``` +ln(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. + Can be a constant, column, or function, and any combination of arithmetic operators. + +##### `log10` + +Returns the base-10 logarithm of a number. + +``` +log10(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. + Can be a constant, column, or function, and any combination of arithmetic operators. + +##### `log2` + +Returns the base-2 logarithm of a number. + +``` +log2(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. + Can be a constant, column, or function, and any combination of arithmetic operators. + +##### `nanvl` + +Returns the first argument if it's not _NaN_. +Returns the second argument otherwise. + +``` +nanvl(expression_x, expression_y) +``` + +###### Arguments + +- **expression_x**: Numeric expression to return if it's not _NaN_. + Can be a constant, column, or function, and any combination of arithmetic operators. +- **expression_y**: Numeric expression to return if the first expression is _NaN_. + Can be a constant, column, or function, and any combination of arithmetic operators. + +##### `pi` + +Returns an approximate value of π. + +``` +pi() +``` + +##### `power` + +Returns a base expression raised to the power of an exponent. + +``` +power(base, exponent) +``` + +###### Arguments + +- **base**: Numeric expression to operate on. + Can be a constant, column, or function, and any combination of arithmetic operators. +- **exponent**: Exponent numeric expression to operate on. + Can be a constant, column, or function, and any combination of arithmetic operators. + +###### Aliases + +- pow + +##### `pow` + +_Alias of [power](#power)._ + +##### `radians` + +Converts degrees to radians. + +``` +radians(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. + Can be a constant, column, or function, and any combination of arithmetic operators. + +##### `random` + +Returns a random float value in the range [0, 1). +The random seed is unique to each row. + +``` +random() +``` + +##### `round` + +Rounds a number to the nearest integer. + +``` +round(numeric_expression[, decimal_places]) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. + Can be a constant, column, or function, and any combination of arithmetic operators. +- **decimal_places**: Optional. The number of decimal places to round to. + Defaults to 0. + +##### `signum` + +Returns the sign of a number. +Negative numbers return `-1`. +Zero and positive numbers return `1`. + +``` +signum(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. + Can be a constant, column, or function, and any combination of arithmetic operators. + +##### `sin` + +Returns the sine of a number. + +``` +sin(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. + Can be a constant, column, or function, and any combination of arithmetic operators. + +##### `sinh` + +Returns the hyperbolic sine of a number. + +``` +sinh(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. + Can be a constant, column, or function, and any combination of arithmetic operators. + +##### `sqrt` + +Returns the square root of a number. + +``` +sqrt(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. + Can be a constant, column, or function, and any combination of arithmetic operators. + +##### `tan` + +Returns the tangent of a number. + +``` +tan(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. + Can be a constant, column, or function, and any combination of arithmetic operators. + +##### `tanh` + +Returns the hyperbolic tangent of a number. + +``` +tanh(numeric_expression) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. + Can be a constant, column, or function, and any combination of arithmetic operators. + +##### `trunc` + +Truncates a number to a whole number or truncated to the specified decimal places. + +``` +trunc(numeric_expression[, decimal_places]) +``` + +###### Arguments + +- **numeric_expression**: Numeric expression to operate on. + Can be a constant, column, or function, and any combination of arithmetic operators. + +- **decimal_places**: Optional. The number of decimal places to + truncate to. Defaults to 0 (truncate to a whole number). If + `decimal_places` is a positive integer, truncates digits to the + right of the decimal point. If `decimal_places` is a negative + integer, replaces digits to the left of the decimal point with `0`. + +### Conditional Functions + +See the new documentation [`here`](https://datafusion.apache.org/user-guide/sql/scalar_functions_new.html) + +### String Functions + +See the new documentation [`here`](https://datafusion.apache.org/user-guide/sql/scalar_functions_new.html) + +##### `position` + +Returns the position of `substr` in `origstr` (counting from 1). If `substr` does +not appear in `origstr`, return 0. + +``` +position(substr in origstr) +``` + +###### Arguments + +- **substr**: The pattern string. +- **origstr**: The model string. + +### Time and Date Functions + +- [now](#now) +- [current_date](#current-date) +- [current_time](#current-time) +- [date_bin](#date-bin) +- [date_trunc](#date-trunc) +- [datetrunc](#datetrunc) +- [date_part](#date-part) +- [datepart](#datepart) +- [extract](#extract) +- [today](#today) +- [make_date](#make-date) +- [to_char](#to-char) +- [to_local_time](#to-local-time) +- [to_timestamp](#to-timestamp) +- [to_timestamp_millis](#to-timestamp-millis) +- [to_timestamp_micros](#to-timestamp-micros) +- [to_timestamp_seconds](#to-timestamp-seconds) +- [to_timestamp_nanos](#to-timestamp-nanos) +- [from_unixtime](#from-unixtime) +- [to_unixtime](#to-unixtime) + +##### `now` + +Returns the current UTC timestamp. + +The `now()` return value is determined at query time and will return the same timestamp, +no matter when in the query plan the function executes. + +``` +now() +``` + +##### `current_date` + +Returns the current UTC date. + +The `current_date()` return value is determined at query time and will return the same date, +no matter when in the query plan the function executes. + +``` +current_date() +``` + +###### Aliases + +- today + +##### `today` + +_Alias of [current_date](#current-date)._ + +##### `current_time` + +Returns the current UTC time. + +The `current_time()` return value is determined at query time and will return the same time, +no matter when in the query plan the function executes. + +``` +current_time() +``` + +##### `date_bin` + +Calculates time intervals and returns the start of the interval nearest to the specified timestamp. +Use `date_bin` to downsample time series data by grouping rows into time-based "bins" or "windows" +and applying an aggregate or selector function to each window. + +For example, if you "bin" or "window" data into 15 minute intervals, an input +timestamp of `2023-01-01T18:18:18Z` will be updated to the start time of the 15 +minute bin it is in: `2023-01-01T18:15:00Z`. + +``` +date_bin(interval, expression, origin-timestamp) +``` + +###### Arguments + +- **interval**: Bin interval. +- **expression**: Time expression to operate on. + Can be a constant, column, or function. +- **origin-timestamp**: Optional. Starting point used to determine bin boundaries. If not specified + defaults `1970-01-01T00:00:00Z` (the UNIX epoch in UTC). + +The following intervals are supported: + +- nanoseconds +- microseconds +- milliseconds +- seconds +- minutes +- hours +- days +- weeks +- months +- years +- century + +##### `date_trunc` + +Truncates a timestamp value to a specified precision. + +``` +date_trunc(precision, expression) +``` + +###### Arguments + +- **precision**: Time precision to truncate to. + The following precisions are supported: + + - year / YEAR + - quarter / QUARTER + - month / MONTH + - week / WEEK + - day / DAY + - hour / HOUR + - minute / MINUTE + - second / SECOND + +- **expression**: Time expression to operate on. + Can be a constant, column, or function. + +###### Aliases + +- datetrunc + +##### `datetrunc` + +_Alias of [date_trunc](#date-trunc)._ + +##### `date_part` + +Returns the specified part of the date as an integer. + +``` +date_part(part, expression) +``` + +###### Arguments + +- **part**: Part of the date to return. + The following date parts are supported: + + - year + - quarter _(emits value in inclusive range [1, 4] based on which quartile of the year the date is in)_ + - month + - week _(week of the year)_ + - day _(day of the month)_ + - hour + - minute + - second + - millisecond + - microsecond + - nanosecond + - dow _(day of the week)_ + - doy _(day of the year)_ + - epoch _(seconds since Unix epoch)_ + +- **expression**: Time expression to operate on. + Can be a constant, column, or function. + +###### Aliases + +- datepart + +##### `datepart` + +_Alias of [date_part](#date-part)._ + +##### `extract` + +Returns a sub-field from a time value as an integer. + +``` +extract(field FROM source) +``` + +Equivalent to calling `date_part('field', source)`. For example, these are equivalent: + +```sql +extract(day FROM '2024-04-13'::date) +date_part('day', '2024-04-13'::date) +``` + +See [date_part](#date-part). + +##### `make_date` + +Make a date from year/month/day component parts. + +``` +make_date(year, month, day) +``` + +###### Arguments + +- **year**: Year to use when making the date. + Can be a constant, column or function, and any combination of arithmetic operators. +- **month**: Month to use when making the date. + Can be a constant, column or function, and any combination of arithmetic operators. +- **day**: Day to use when making the date. + Can be a constant, column or function, and any combination of arithmetic operators. + +###### Example + +``` +> select make_date(2023, 1, 31); ++-------------------------------------------+ +| make_date(Int64(2023),Int64(1),Int64(31)) | ++-------------------------------------------+ +| 2023-01-31 | ++-------------------------------------------+ +> select make_date('2023', '01', '31'); ++-----------------------------------------------+ +| make_date(Utf8("2023"),Utf8("01"),Utf8("31")) | ++-----------------------------------------------+ +| 2023-01-31 | ++-----------------------------------------------+ +``` + +Additional examples can be found [here](https://github.com/apache/datafusion/blob/main/datafusion-examples/examples/make_date.rs) + +##### `to_char` + +Returns a string representation of a date, time, timestamp or duration based +on a [Chrono format]. Unlike the PostgreSQL equivalent of this function +numerical formatting is not supported. + +``` +to_char(expression, format) +``` + +###### Arguments + +- **expression**: Expression to operate on. + Can be a constant, column, or function that results in a + date, time, timestamp or duration. +- **format**: A [Chrono format] string to use to convert the expression. + +###### Example + +``` +> select to_char('2023-03-01'::date, '%d-%m-%Y'); ++----------------------------------------------+ +| to_char(Utf8("2023-03-01"),Utf8("%d-%m-%Y")) | ++----------------------------------------------+ +| 01-03-2023 | ++----------------------------------------------+ +``` + +Additional examples can be found [here] + +[here]: https://github.com/apache/datafusion/blob/main/datafusion-examples/examples/to_char.rs + +###### Aliases + +- date_format + +##### `to_local_time` + +Converts a timestamp with a timezone to a timestamp without a timezone (with no offset or +timezone information). This function handles daylight saving time changes. + +``` +to_local_time(expression) +``` + +###### Arguments + +- **expression**: Time expression to operate on. Can be a constant, column, or function. + +###### Example + +``` +> SELECT to_local_time('2024-04-01T00:00:20Z'::timestamp); ++---------------------------------------------+ +| to_local_time(Utf8("2024-04-01T00:00:20Z")) | ++---------------------------------------------+ +| 2024-04-01T00:00:20 | ++---------------------------------------------+ + +> SELECT to_local_time('2024-04-01T00:00:20Z'::timestamp AT TIME ZONE 'Europe/Brussels'); ++---------------------------------------------+ +| to_local_time(Utf8("2024-04-01T00:00:20Z")) | ++---------------------------------------------+ +| 2024-04-01T00:00:20 | ++---------------------------------------------+ + +> SELECT + time, + arrow_typeof(time) as type, + to_local_time(time) as to_local_time, + arrow_typeof(to_local_time(time)) as to_local_time_type +FROM ( + SELECT '2024-04-01T00:00:20Z'::timestamp AT TIME ZONE 'Europe/Brussels' AS time +); ++---------------------------+------------------------------------------------+---------------------+-----------------------------+ +| time | type | to_local_time | to_local_time_type | ++---------------------------+------------------------------------------------+---------------------+-----------------------------+ +| 2024-04-01T00:00:20+02:00 | Timestamp(Nanosecond, Some("Europe/Brussels")) | 2024-04-01T00:00:20 | Timestamp(Nanosecond, None) | ++---------------------------+------------------------------------------------+---------------------+-----------------------------+ + +## combine `to_local_time()` with `date_bin()` to bin on boundaries in the timezone rather +## than UTC boundaries + +> SELECT date_bin(interval '1 day', to_local_time('2024-04-01T00:00:20Z'::timestamp AT TIME ZONE 'Europe/Brussels')) AS date_bin; ++---------------------+ +| date_bin | ++---------------------+ +| 2024-04-01T00:00:00 | ++---------------------+ + +> SELECT date_bin(interval '1 day', to_local_time('2024-04-01T00:00:20Z'::timestamp AT TIME ZONE 'Europe/Brussels')) AT TIME ZONE 'Europe/Brussels' AS date_bin_with_timezone; ++---------------------------+ +| date_bin_with_timezone | ++---------------------------+ +| 2024-04-01T00:00:00+02:00 | ++---------------------------+ +``` + +##### `to_timestamp` + +Converts a value to a timestamp (`YYYY-MM-DDT00:00:00Z`). +Supports strings, integer, unsigned integer, and double types as input. +Strings are parsed as RFC3339 (e.g. '2023-07-20T05:44:00') if no [Chrono formats] are provided. +Integers, unsigned integers, and doubles are interpreted as seconds since the unix epoch (`1970-01-01T00:00:00Z`). +Returns the corresponding timestamp. + +Note: `to_timestamp` returns `Timestamp(Nanosecond)`. The supported range for integer input is between `-9223372037` and `9223372036`. +Supported range for string input is between `1677-09-21T00:12:44.0` and `2262-04-11T23:47:16.0`. Please use `to_timestamp_seconds` +for the input outside of supported bounds. + +``` +to_timestamp(expression[, ..., format_n]) +``` + +###### Arguments + +- **expression**: Expression to operate on. + Can be a constant, column, or function, and any combination of arithmetic operators. +- **format_n**: Optional [Chrono format] strings to use to parse the expression. Formats will be tried in the order + they appear with the first successful one being returned. If none of the formats successfully parse the expression + an error will be returned. + +[chrono format]: https://docs.rs/chrono/latest/chrono/format/strftime/index.html + +###### Example + +``` +> select to_timestamp('2023-01-31T09:26:56.123456789-05:00'); ++-----------------------------------------------------------+ +| to_timestamp(Utf8("2023-01-31T09:26:56.123456789-05:00")) | ++-----------------------------------------------------------+ +| 2023-01-31T14:26:56.123456789 | ++-----------------------------------------------------------+ +> select to_timestamp('03:59:00.123456789 05-17-2023', '%c', '%+', '%H:%M:%S%.f %m-%d-%Y'); ++--------------------------------------------------------------------------------------------------------+ +| to_timestamp(Utf8("03:59:00.123456789 05-17-2023"),Utf8("%c"),Utf8("%+"),Utf8("%H:%M:%S%.f %m-%d-%Y")) | ++--------------------------------------------------------------------------------------------------------+ +| 2023-05-17T03:59:00.123456789 | ++--------------------------------------------------------------------------------------------------------+ +``` + +Additional examples can be found [here](https://github.com/apache/datafusion/blob/main/datafusion-examples/examples/to_timestamp.rs) + +##### `to_timestamp_millis` + +Converts a value to a timestamp (`YYYY-MM-DDT00:00:00.000Z`). +Supports strings, integer, and unsigned integer types as input. +Strings are parsed as RFC3339 (e.g. '2023-07-20T05:44:00') if no [Chrono format]s are provided. +Integers and unsigned integers are interpreted as milliseconds since the unix epoch (`1970-01-01T00:00:00Z`). +Returns the corresponding timestamp. + +``` +to_timestamp_millis(expression[, ..., format_n]) +``` + +###### Arguments + +- **expression**: Expression to operate on. + Can be a constant, column, or function, and any combination of arithmetic operators. +- **format_n**: Optional [Chrono format] strings to use to parse the expression. Formats will be tried in the order + they appear with the first successful one being returned. If none of the formats successfully parse the expression + an error will be returned. + +###### Example + +``` +> select to_timestamp_millis('2023-01-31T09:26:56.123456789-05:00'); ++------------------------------------------------------------------+ +| to_timestamp_millis(Utf8("2023-01-31T09:26:56.123456789-05:00")) | ++------------------------------------------------------------------+ +| 2023-01-31T14:26:56.123 | ++------------------------------------------------------------------+ +> select to_timestamp_millis('03:59:00.123456789 05-17-2023', '%c', '%+', '%H:%M:%S%.f %m-%d-%Y'); ++---------------------------------------------------------------------------------------------------------------+ +| to_timestamp_millis(Utf8("03:59:00.123456789 05-17-2023"),Utf8("%c"),Utf8("%+"),Utf8("%H:%M:%S%.f %m-%d-%Y")) | ++---------------------------------------------------------------------------------------------------------------+ +| 2023-05-17T03:59:00.123 | ++---------------------------------------------------------------------------------------------------------------+ +``` + +Additional examples can be found [here](https://github.com/apache/datafusion/blob/main/datafusion-examples/examples/to_timestamp.rs) + +##### `to_timestamp_micros` + +Converts a value to a timestamp (`YYYY-MM-DDT00:00:00.000000Z`). +Supports strings, integer, and unsigned integer types as input. +Strings are parsed as RFC3339 (e.g. '2023-07-20T05:44:00') if no [Chrono format]s are provided. +Integers and unsigned integers are interpreted as microseconds since the unix epoch (`1970-01-01T00:00:00Z`) +Returns the corresponding timestamp. + +``` +to_timestamp_micros(expression[, ..., format_n]) +``` + +###### Arguments + +- **expression**: Expression to operate on. + Can be a constant, column, or function, and any combination of arithmetic operators. +- **format_n**: Optional [Chrono format] strings to use to parse the expression. Formats will be tried in the order + they appear with the first successful one being returned. If none of the formats successfully parse the expression + an error will be returned. + +###### Example + +``` +> select to_timestamp_micros('2023-01-31T09:26:56.123456789-05:00'); ++------------------------------------------------------------------+ +| to_timestamp_micros(Utf8("2023-01-31T09:26:56.123456789-05:00")) | ++------------------------------------------------------------------+ +| 2023-01-31T14:26:56.123456 | ++------------------------------------------------------------------+ +> select to_timestamp_micros('03:59:00.123456789 05-17-2023', '%c', '%+', '%H:%M:%S%.f %m-%d-%Y'); ++---------------------------------------------------------------------------------------------------------------+ +| to_timestamp_micros(Utf8("03:59:00.123456789 05-17-2023"),Utf8("%c"),Utf8("%+"),Utf8("%H:%M:%S%.f %m-%d-%Y")) | ++---------------------------------------------------------------------------------------------------------------+ +| 2023-05-17T03:59:00.123456 | ++---------------------------------------------------------------------------------------------------------------+ +``` + +Additional examples can be found [here](https://github.com/apache/datafusion/blob/main/datafusion-examples/examples/to_timestamp.rs) + +##### `to_timestamp_nanos` + +Converts a value to a timestamp (`YYYY-MM-DDT00:00:00.000000000Z`). +Supports strings, integer, and unsigned integer types as input. +Strings are parsed as RFC3339 (e.g. '2023-07-20T05:44:00') if no [Chrono format]s are provided. +Integers and unsigned integers are interpreted as nanoseconds since the unix epoch (`1970-01-01T00:00:00Z`). +Returns the corresponding timestamp. + +``` +to_timestamp_nanos(expression[, ..., format_n]) +``` + +###### Arguments + +- **expression**: Expression to operate on. + Can be a constant, column, or function, and any combination of arithmetic operators. +- **format_n**: Optional [Chrono format] strings to use to parse the expression. Formats will be tried in the order + they appear with the first successful one being returned. If none of the formats successfully parse the expression + an error will be returned. + +###### Example + +``` +> select to_timestamp_nanos('2023-01-31T09:26:56.123456789-05:00'); ++-----------------------------------------------------------------+ +| to_timestamp_nanos(Utf8("2023-01-31T09:26:56.123456789-05:00")) | ++-----------------------------------------------------------------+ +| 2023-01-31T14:26:56.123456789 | ++-----------------------------------------------------------------+ +> select to_timestamp_nanos('03:59:00.123456789 05-17-2023', '%c', '%+', '%H:%M:%S%.f %m-%d-%Y'); ++--------------------------------------------------------------------------------------------------------------+ +| to_timestamp_nanos(Utf8("03:59:00.123456789 05-17-2023"),Utf8("%c"),Utf8("%+"),Utf8("%H:%M:%S%.f %m-%d-%Y")) | ++--------------------------------------------------------------------------------------------------------------+ +| 2023-05-17T03:59:00.123456789 | ++---------------------------------------------------------------------------------------------------------------+ +``` + +Additional examples can be found [here](https://github.com/apache/datafusion/blob/main/datafusion-examples/examples/to_timestamp.rs) + +##### `to_timestamp_seconds` + +Converts a value to a timestamp (`YYYY-MM-DDT00:00:00.000Z`). +Supports strings, integer, and unsigned integer types as input. +Strings are parsed as RFC3339 (e.g. '2023-07-20T05:44:00') if no [Chrono format]s are provided. +Integers and unsigned integers are interpreted as seconds since the unix epoch (`1970-01-01T00:00:00Z`). +Returns the corresponding timestamp. + +``` +to_timestamp_seconds(expression[, ..., format_n]) +``` + +###### Arguments + +- **expression**: Expression to operate on. + Can be a constant, column, or function, and any combination of arithmetic operators. +- **format_n**: Optional [Chrono format] strings to use to parse the expression. Formats will be tried in the order + they appear with the first successful one being returned. If none of the formats successfully parse the expression + an error will be returned. + +###### Example + +``` +> select to_timestamp_seconds('2023-01-31T09:26:56.123456789-05:00'); ++-------------------------------------------------------------------+ +| to_timestamp_seconds(Utf8("2023-01-31T09:26:56.123456789-05:00")) | ++-------------------------------------------------------------------+ +| 2023-01-31T14:26:56 | ++-------------------------------------------------------------------+ +> select to_timestamp_seconds('03:59:00.123456789 05-17-2023', '%c', '%+', '%H:%M:%S%.f %m-%d-%Y'); ++----------------------------------------------------------------------------------------------------------------+ +| to_timestamp_seconds(Utf8("03:59:00.123456789 05-17-2023"),Utf8("%c"),Utf8("%+"),Utf8("%H:%M:%S%.f %m-%d-%Y")) | ++----------------------------------------------------------------------------------------------------------------+ +| 2023-05-17T03:59:00 | ++----------------------------------------------------------------------------------------------------------------+ +``` + +Additional examples can be found [here](https://github.com/apache/datafusion/blob/main/datafusion-examples/examples/to_timestamp.rs) + +##### `from_unixtime` + +Converts an integer to RFC3339 timestamp format (`YYYY-MM-DDT00:00:00.000000000Z`). +Integers and unsigned integers are interpreted as nanoseconds since the unix epoch (`1970-01-01T00:00:00Z`) +return the corresponding timestamp. + +``` +from_unixtime(expression) +``` + +###### Arguments + +- **expression**: Expression to operate on. + Can be a constant, column, or function, and any combination of arithmetic operators. + +##### `to_unixtime` + +Converts a value to seconds since the unix epoch (`1970-01-01T00:00:00Z`). +Supports strings, dates, timestamps and double types as input. +Strings are parsed as RFC3339 (e.g. '2023-07-20T05:44:00') if no [Chrono formats] are provided. + +``` +to_unixtime(expression[, ..., format_n]) +``` + +###### Arguments + +- **expression**: Expression to operate on. + Can be a constant, column, or function, and any combination of arithmetic operators. +- **format_n**: Optional [Chrono format] strings to use to parse the expression. Formats will be tried in the order + they appear with the first successful one being returned. If none of the formats successfully parse the expression + an error will be returned. + +###### Example + +``` +> select to_unixtime('2020-09-08T12:00:00+00:00'); ++------------------------------------------------+ +| to_unixtime(Utf8("2020-09-08T12:00:00+00:00")) | ++------------------------------------------------+ +| 1599566400 | ++------------------------------------------------+ +> select to_unixtime('01-14-2023 01:01:30+05:30', '%q', '%d-%m-%Y %H/%M/%S', '%+', '%m-%d-%Y %H:%M:%S%#z'); ++-----------------------------------------------------------------------------------------------------------------------------+ +| to_unixtime(Utf8("01-14-2023 01:01:30+05:30"),Utf8("%q"),Utf8("%d-%m-%Y %H/%M/%S"),Utf8("%+"),Utf8("%m-%d-%Y %H:%M:%S%#z")) | ++-----------------------------------------------------------------------------------------------------------------------------+ +| 1673638290 | ++-----------------------------------------------------------------------------------------------------------------------------+ +``` + +### Array Functions + +- [array_any_value](#array-any-value) +- [array_append](#array-append) +- [array_sort](#array-sort) +- [array_cat](#array-cat) +- [array_concat](#array-concat) +- [array_contains](#array-contains) +- [array_dims](#array-dims) +- [array_distance](#array-distance) +- [array_distinct](#array-distinct) +- [array_has](#array-has) +- [array_has_all](#array-has-all) +- [array_has_any](#array-has-any) +- [array_element](#array-element) +- [array_empty](#array-empty) +- [array_except](#array-except) +- [array_extract](#array-extract) +- [array_fill](#array-fill) +- [array_indexof](#array-indexof) +- [array_intersect](#array-intersect) +- [array_join](#array-join) +- [array_length](#array-length) +- [array_ndims](#array-ndims) +- [array_prepend](#array-prepend) +- [array_pop_front](#array-pop-front) +- [array_pop_back](#array-pop-back) +- [array_position](#array-position) +- [array_positions](#array-positions) +- [array_push_back](#array-push-back) +- [array_push_front](#array-push-front) +- [array_repeat](#array-repeat) +- [array_resize](#array-resize) +- [array_remove](#array-remove) +- [array_remove_n](#array-remove-n) +- [array_remove_all](#array-remove-all) +- [array_replace](#array-replace) +- [array_replace_n](#array-replace-n) +- [array_replace_all](#array-replace-all) +- [array_reverse](#array-reverse) +- [array_slice](#array-slice) +- [array_to_string](#array-to-string) +- [array_union](#array-union) +- [cardinality](#cardinality) +- [empty](#empty) +- [flatten](#flatten) +- [generate_series](#generate-series) +- [list_any_value](#list-any-value) +- [list_append](#list-append) +- [list_sort](#list-sort) +- [list_cat](#list-cat) +- [list_concat](#list-concat) +- [list_dims](#list-dims) +- [list_distance](#list-distance) +- [list_distinct](#list-distinct) +- [list_element](#list-element) +- [list_except](#list-except) +- [list_extract](#list-extract) +- [list_has](#list-has) +- [list_has_all](#list-has-all) +- [list_has_any](#list-has-any) +- [list_indexof](#list-indexof) +- [list_intersect](#list-intersect) +- [list_join](#list-join) +- [list_length](#list-length) +- [list_ndims](#list-ndims) +- [list_prepend](#list-prepend) +- [list_pop_back](#list-pop-back) +- [list_pop_front](#list-pop-front) +- [list_position](#list-position) +- [list_positions](#list-positions) +- [list_push_back](#list-push-back) +- [list_push_front](#list-push-front) +- [list_repeat](#list-repeat) +- [list_resize](#list-resize) +- [list_remove](#list-remove) +- [list_remove_n](#list-remove-n) +- [list_remove_all](#list-remove-all) +- [list_replace](#list-replace) +- [list_replace_n](#list-replace-n) +- [list_replace_all](#list-replace-all) +- [list_slice](#list-slice) +- [list_to_string](#list-to-string) +- [list_union](#list-union) +- [make_array](#make-array) +- [make_list](#make-list) +- [string_to_array](#string-to-array) +- [string_to_list](#string-to-list) +- [trim_array](#trim-array) +- [unnest](#unnest) +- [range](#range) + +##### `array_any_value` + +Returns the first non-null element in the array. + +``` +array_any_value(array) +``` + +###### Arguments + +- **array**: Array expression. + Can be a constant, column, or function, and any combination of array operators. + +###### Example + +``` +> select array_any_value([NULL, 1, 2, 3]); ++--------------------------------------------------------------+ +| array_any_value(List([NULL,1,2,3])) | ++--------------------------------------------------------------+ +| 1 | ++--------------------------------------------------------------+ +``` + +##### `array_append` + +Appends an element to the end of an array. + +``` +array_append(array, element) +``` + +###### Arguments + +- **array**: Array expression. + Can be a constant, column, or function, and any combination of array operators. +- **element**: Element to append to the array. + +###### Example + +``` +> select array_append([1, 2, 3], 4); ++--------------------------------------+ +| array_append(List([1,2,3]),Int64(4)) | ++--------------------------------------+ +| [1, 2, 3, 4] | ++--------------------------------------+ +``` + +###### Aliases + +- array_push_back +- list_append +- list_push_back + +##### `array_sort` + +Sort array. + +``` +array_sort(array, desc, nulls_first) +``` + +###### Arguments + +- **array**: Array expression. + Can be a constant, column, or function, and any combination of array operators. +- **desc**: Whether to sort in descending order(`ASC` or `DESC`). +- **nulls_first**: Whether to sort nulls first(`NULLS FIRST` or `NULLS LAST`). + +###### Example + +``` +> select array_sort([3, 1, 2]); ++-----------------------------+ +| array_sort(List([3,1,2])) | ++-----------------------------+ +| [1, 2, 3] | ++-----------------------------+ +``` + +###### Aliases + +- list_sort + +##### `array_resize` + +Resizes the list to contain size elements. Initializes new elements with value or empty if value is not set. + +``` +array_resize(array, size, value) +``` + +###### Arguments + +- **array**: Array expression. + Can be a constant, column, or function, and any combination of array operators. +- **size**: New size of given array. +- **value**: Defines new elements' value or empty if value is not set. + +###### Example + +``` +> select array_resize([1, 2, 3], 5, 0); ++-------------------------------------+ +| array_resize(List([1,2,3],5,0)) | ++-------------------------------------+ +| [1, 2, 3, 0, 0] | ++-------------------------------------+ +``` + +###### Aliases + +- list_resize + +##### `array_cat` + +_Alias of [array_concat](#array-concat)._ + +##### `array_concat` + +Concatenates arrays. + +``` +array_concat(array[, ..., array_n]) +``` + +###### Arguments + +- **array**: Array expression to concatenate. + Can be a constant, column, or function, and any combination of array operators. +- **array_n**: Subsequent array column or literal array to concatenate. + +###### Example + +``` +> select array_concat([1, 2], [3, 4], [5, 6]); ++---------------------------------------------------+ +| array_concat(List([1,2]),List([3,4]),List([5,6])) | ++---------------------------------------------------+ +| [1, 2, 3, 4, 5, 6] | ++---------------------------------------------------+ +``` + +###### Aliases + +- array_cat +- list_cat +- list_concat + +##### `array_contains` + +_Alias of [array_has](#array-has)._ + +##### `array_has` + +Returns true if the array contains the element + +``` +array_has(array, element) +``` + +###### Arguments + +- **array**: Array expression. + Can be a constant, column, or function, and any combination of array operators. +- **element**: Scalar or Array expression. + Can be a constant, column, or function, and any combination of array operators. + +###### Aliases + +- list_has + +##### `array_has_all` + +Returns true if all elements of sub-array exist in array + +``` +array_has_all(array, sub-array) +``` + +###### Arguments + +- **array**: Array expression. + Can be a constant, column, or function, and any combination of array operators. +- **sub-array**: Array expression. + Can be a constant, column, or function, and any combination of array operators. + +###### Aliases + +- list_has_all + +##### `array_has_any` + +Returns true if any elements exist in both arrays + +``` +array_has_any(array, sub-array) +``` + +###### Arguments + +- **array**: Array expression. + Can be a constant, column, or function, and any combination of array operators. +- **sub-array**: Array expression. + Can be a constant, column, or function, and any combination of array operators. + +###### Aliases + +- list_has_any + +##### `array_dims` + +Returns an array of the array's dimensions. + +``` +array_dims(array) +``` + +###### Arguments + +- **array**: Array expression. + Can be a constant, column, or function, and any combination of array operators. + +###### Example + +``` +> select array_dims([[1, 2, 3], [4, 5, 6]]); ++---------------------------------+ +| array_dims(List([1,2,3,4,5,6])) | ++---------------------------------+ +| [2, 3] | ++---------------------------------+ +``` + +###### Aliases + +- list_dims + +##### `array_distance` + +Returns the Euclidean distance between two input arrays of equal length. + +``` +array_distance(array1, array2) +``` + +###### Arguments + +- **array1**: Array expression. + Can be a constant, column, or function, and any combination of array operators. +- **array2**: Array expression. + Can be a constant, column, or function, and any combination of array operators. + +###### Example + +``` +> select array_distance([1, 2], [1, 4]); ++------------------------------------+ +| array_distance(List([1,2], [1,4])) | ++------------------------------------+ +| 2.0 | ++------------------------------------+ +``` + +###### Aliases + +- list_distance + +##### `array_distinct` + +Returns distinct values from the array after removing duplicates. + +``` +array_distinct(array) +``` + +###### Arguments + +- **array**: Array expression. + Can be a constant, column, or function, and any combination of array operators. + +###### Example + +``` +> select array_distinct([1, 3, 2, 3, 1, 2, 4]); ++---------------------------------+ +| array_distinct(List([1,2,3,4])) | ++---------------------------------+ +| [1, 2, 3, 4] | ++---------------------------------+ +``` + +###### Aliases + +- list_distinct + +##### `array_element` + +Extracts the element with the index n from the array. + +``` +array_element(array, index) +``` + +###### Arguments + +- **array**: Array expression. + Can be a constant, column, or function, and any combination of array operators. +- **index**: Index to extract the element from the array. + +###### Example + +``` +> select array_element([1, 2, 3, 4], 3); ++-----------------------------------------+ +| array_element(List([1,2,3,4]),Int64(3)) | ++-----------------------------------------+ +| 3 | ++-----------------------------------------+ +``` + +###### Aliases + +- array_extract +- list_element +- list_extract + +##### `array_extract` + +_Alias of [array_element](#array-element)._ + +##### `array_fill` + +Returns an array filled with copies of the given value. + +DEPRECATED: use `array_repeat` instead! + +``` +array_fill(element, array) +``` + +###### Arguments + +- **array**: Array expression. + Can be a constant, column, or function, and any combination of array operators. +- **element**: Element to copy to the array. + +##### `flatten` + +Converts an array of arrays to a flat array + +- Applies to any depth of nested arrays +- Does not change arrays that are already flat + +The flattened array contains all the elements from all source arrays. + +###### Arguments + +- **array**: Array expression + Can be a constant, column, or function, and any combination of array operators. + +``` +flatten(array) +``` + +##### `array_indexof` + +_Alias of [array_position](#array-position)._ + +##### `array_intersect` + +Returns an array of elements in the intersection of array1 and array2. + +``` +array_intersect(array1, array2) +``` + +###### Arguments + +- **array1**: Array expression. + Can be a constant, column, or function, and any combination of array operators. +- **array2**: Array expression. + Can be a constant, column, or function, and any combination of array operators. + +###### Example + +``` +> select array_intersect([1, 2, 3, 4], [5, 6, 3, 4]); ++----------------------------------------------------+ +| array_intersect([1, 2, 3, 4], [5, 6, 3, 4]); | ++----------------------------------------------------+ +| [3, 4] | ++----------------------------------------------------+ +> select array_intersect([1, 2, 3, 4], [5, 6, 7, 8]); ++----------------------------------------------------+ +| array_intersect([1, 2, 3, 4], [5, 6, 7, 8]); | ++----------------------------------------------------+ +| [] | ++----------------------------------------------------+ +``` + +--- + +###### Aliases + +- list_intersect + +##### `array_join` + +_Alias of [array_to_string](#array-to-string)._ + +##### `array_length` + +Returns the length of the array dimension. + +``` +array_length(array, dimension) +``` + +###### Arguments + +- **array**: Array expression. + Can be a constant, column, or function, and any combination of array operators. +- **dimension**: Array dimension. + +###### Example + +``` +> select array_length([1, 2, 3, 4, 5]); ++---------------------------------+ +| array_length(List([1,2,3,4,5])) | ++---------------------------------+ +| 5 | ++---------------------------------+ +``` + +###### Aliases + +- list_length + +##### `array_ndims` + +Returns the number of dimensions of the array. + +``` +array_ndims(array, element) +``` + +###### Arguments + +- **array**: Array expression. + Can be a constant, column, or function, and any combination of array operators. + +###### Example + +``` +> select array_ndims([[1, 2, 3], [4, 5, 6]]); ++----------------------------------+ +| array_ndims(List([1,2,3,4,5,6])) | ++----------------------------------+ +| 2 | ++----------------------------------+ +``` + +###### Aliases + +- list_ndims + +##### `array_prepend` + +Prepends an element to the beginning of an array. + +``` +array_prepend(element, array) +``` + +###### Arguments + +- **element**: Element to prepend to the array. +- **array**: Array expression. + Can be a constant, column, or function, and any combination of array operators. + +###### Example + +``` +> select array_prepend(1, [2, 3, 4]); ++---------------------------------------+ +| array_prepend(Int64(1),List([2,3,4])) | ++---------------------------------------+ +| [1, 2, 3, 4] | ++---------------------------------------+ +``` + +###### Aliases + +- array_push_front +- list_prepend +- list_push_front + +##### `array_pop_front` + +Returns the array without the first element. + +``` +array_pop_front(array) +``` + +###### Arguments + +- **array**: Array expression. + Can be a constant, column, or function, and any combination of array operators. + +###### Example + +``` +> select array_pop_front([1, 2, 3]); ++-------------------------------+ +| array_pop_front(List([1,2,3])) | ++-------------------------------+ +| [2, 3] | ++-------------------------------+ +``` + +###### Aliases + +- list_pop_front + +##### `array_pop_back` + +Returns the array without the last element. + +``` +array_pop_back(array) +``` + +###### Arguments + +- **array**: Array expression. + Can be a constant, column, or function, and any combination of array operators. + +###### Example + +``` +> select array_pop_back([1, 2, 3]); ++-------------------------------+ +| array_pop_back(List([1,2,3])) | ++-------------------------------+ +| [1, 2] | ++-------------------------------+ +``` + +###### Aliases + +- list_pop_back + +##### `array_position` + +Returns the position of the first occurrence of the specified element in the array. + +``` +array_position(array, element) +array_position(array, element, index) +``` + +###### Arguments + +- **array**: Array expression. + Can be a constant, column, or function, and any combination of array operators. +- **element**: Element to search for position in the array. +- **index**: Index at which to start searching. + +###### Example + +``` +> select array_position([1, 2, 2, 3, 1, 4], 2); ++----------------------------------------------+ +| array_position(List([1,2,2,3,1,4]),Int64(2)) | ++----------------------------------------------+ +| 2 | ++----------------------------------------------+ +``` + +###### Aliases + +- array_indexof +- list_indexof +- list_position + +##### `array_positions` + +Searches for an element in the array, returns all occurrences. + +``` +array_positions(array, element) +``` + +###### Arguments + +- **array**: Array expression. + Can be a constant, column, or function, and any combination of array operators. +- **element**: Element to search for positions in the array. + +###### Example + +``` +> select array_positions([1, 2, 2, 3, 1, 4], 2); ++-----------------------------------------------+ +| array_positions(List([1,2,2,3,1,4]),Int64(2)) | ++-----------------------------------------------+ +| [2, 3] | ++-----------------------------------------------+ +``` + +###### Aliases + +- list_positions + +##### `array_push_back` + +_Alias of [array_append](#array-append)._ + +##### `array_push_front` + +_Alias of [array_prepend](#array-prepend)._ + +##### `array_repeat` + +Returns an array containing element `count` times. + +``` +array_repeat(element, count) +``` + +###### Arguments + +- **element**: Element expression. + Can be a constant, column, or function, and any combination of array operators. +- **count**: Value of how many times to repeat the element. + +###### Example + +``` +> select array_repeat(1, 3); ++---------------------------------+ +| array_repeat(Int64(1),Int64(3)) | ++---------------------------------+ +| [1, 1, 1] | ++---------------------------------+ +``` + +``` +> select array_repeat([1, 2], 2); ++------------------------------------+ +| array_repeat(List([1,2]),Int64(2)) | ++------------------------------------+ +| [[1, 2], [1, 2]] | ++------------------------------------+ +``` + +###### Aliases + +- list_repeat + +##### `array_remove` + +Removes the first element from the array equal to the given value. + +``` +array_remove(array, element) +``` + +###### Arguments + +- **array**: Array expression. + Can be a constant, column, or function, and any combination of array operators. +- **element**: Element to be removed from the array. + +###### Example + +``` +> select array_remove([1, 2, 2, 3, 2, 1, 4], 2); ++----------------------------------------------+ +| array_remove(List([1,2,2,3,2,1,4]),Int64(2)) | ++----------------------------------------------+ +| [1, 2, 3, 2, 1, 4] | ++----------------------------------------------+ +``` + +###### Aliases + +- list_remove + +##### `array_remove_n` + +Removes the first `max` elements from the array equal to the given value. + +``` +array_remove_n(array, element, max) +``` + +###### Arguments + +- **array**: Array expression. + Can be a constant, column, or function, and any combination of array operators. +- **element**: Element to be removed from the array. +- **max**: Number of first occurrences to remove. + +###### Example + +``` +> select array_remove_n([1, 2, 2, 3, 2, 1, 4], 2, 2); ++---------------------------------------------------------+ +| array_remove_n(List([1,2,2,3,2,1,4]),Int64(2),Int64(2)) | ++---------------------------------------------------------+ +| [1, 3, 2, 1, 4] | ++---------------------------------------------------------+ +``` + +###### Aliases + +- list_remove_n + +##### `array_remove_all` + +Removes all elements from the array equal to the given value. + +``` +array_remove_all(array, element) +``` + +###### Arguments + +- **array**: Array expression. + Can be a constant, column, or function, and any combination of array operators. +- **element**: Element to be removed from the array. + +###### Example + +``` +> select array_remove_all([1, 2, 2, 3, 2, 1, 4], 2); ++--------------------------------------------------+ +| array_remove_all(List([1,2,2,3,2,1,4]),Int64(2)) | ++--------------------------------------------------+ +| [1, 3, 1, 4] | ++--------------------------------------------------+ +``` + +###### Aliases + +- list_remove_all + +##### `array_replace` + +Replaces the first occurrence of the specified element with another specified element. + +``` +array_replace(array, from, to) +``` + +###### Arguments + +- **array**: Array expression. + Can be a constant, column, or function, and any combination of array operators. +- **from**: Initial element. +- **to**: Final element. + +###### Example + +``` +> select array_replace([1, 2, 2, 3, 2, 1, 4], 2, 5); ++--------------------------------------------------------+ +| array_replace(List([1,2,2,3,2,1,4]),Int64(2),Int64(5)) | ++--------------------------------------------------------+ +| [1, 5, 2, 3, 2, 1, 4] | ++--------------------------------------------------------+ +``` + +###### Aliases + +- list_replace + +##### `array_replace_n` + +Replaces the first `max` occurrences of the specified element with another specified element. + +``` +array_replace_n(array, from, to, max) +``` + +###### Arguments + +- **array**: Array expression. + Can be a constant, column, or function, and any combination of array operators. +- **from**: Initial element. +- **to**: Final element. +- **max**: Number of first occurrences to replace. + +###### Example + +``` +> select array_replace_n([1, 2, 2, 3, 2, 1, 4], 2, 5, 2); ++-------------------------------------------------------------------+ +| array_replace_n(List([1,2,2,3,2,1,4]),Int64(2),Int64(5),Int64(2)) | ++-------------------------------------------------------------------+ +| [1, 5, 5, 3, 2, 1, 4] | ++-------------------------------------------------------------------+ +``` + +###### Aliases + +- list_replace_n + +##### `array_replace_all` + +Replaces all occurrences of the specified element with another specified element. + +``` +array_replace_all(array, from, to) +``` + +###### Arguments + +- **array**: Array expression. + Can be a constant, column, or function, and any combination of array operators. +- **from**: Initial element. +- **to**: Final element. + +###### Example + +``` +> select array_replace_all([1, 2, 2, 3, 2, 1, 4], 2, 5); ++------------------------------------------------------------+ +| array_replace_all(List([1,2,2,3,2,1,4]),Int64(2),Int64(5)) | ++------------------------------------------------------------+ +| [1, 5, 5, 3, 5, 1, 4] | ++------------------------------------------------------------+ +``` + +###### Aliases + +- list_replace_all + +##### `array_reverse` + +Returns the array with the order of the elements reversed. + +``` +array_reverse(array) +``` + +###### Arguments + +- **array**: Array expression. + Can be a constant, column, or function, and any combination of array operators. + +###### Example + +``` +> select array_reverse([1, 2, 3, 4]); ++------------------------------------------------------------+ +| array_reverse(List([1, 2, 3, 4])) | ++------------------------------------------------------------+ +| [4, 3, 2, 1] | ++------------------------------------------------------------+ +``` + +###### Aliases + +- list_reverse + +##### `array_slice` + +Returns a slice of the array based on 1-indexed start and end positions. + +``` +array_slice(array, begin, end) +``` + +###### Arguments + +- **array**: Array expression. + Can be a constant, column, or function, and any combination of array operators. +- **begin**: Index of the first element. + If negative, it counts backward from the end of the array. +- **end**: Index of the last element. + If negative, it counts backward from the end of the array. +- **stride**: Stride of the array slice. The default is 1. + +###### Example + +``` +> select array_slice([1, 2, 3, 4, 5, 6, 7, 8], 3, 6); ++--------------------------------------------------------+ +| array_slice(List([1,2,3,4,5,6,7,8]),Int64(3),Int64(6)) | ++--------------------------------------------------------+ +| [3, 4, 5, 6] | ++--------------------------------------------------------+ +``` + +###### Aliases + +- list_slice + +##### `array_to_string` + +Converts each element to its text representation. + +``` +array_to_string(array, delimiter) +``` + +###### Arguments + +- **array**: Array expression. + Can be a constant, column, or function, and any combination of array operators. +- **delimiter**: Array element separator. + +###### Example + +``` +> select array_to_string([[1, 2, 3, 4], [5, 6, 7, 8]], ','); ++----------------------------------------------------+ +| array_to_string(List([1,2,3,4,5,6,7,8]),Utf8(",")) | ++----------------------------------------------------+ +| 1,2,3,4,5,6,7,8 | ++----------------------------------------------------+ +``` + +###### Aliases + +- array_join +- list_join +- list_to_string + +##### `array_union` + +Returns an array of elements that are present in both arrays (all elements from both arrays) with out duplicates. + +``` +array_union(array1, array2) +``` + +###### Arguments + +- **array1**: Array expression. + Can be a constant, column, or function, and any combination of array operators. +- **array2**: Array expression. + Can be a constant, column, or function, and any combination of array operators. + +###### Example + +``` +> select array_union([1, 2, 3, 4], [5, 6, 3, 4]); ++----------------------------------------------------+ +| array_union([1, 2, 3, 4], [5, 6, 3, 4]); | ++----------------------------------------------------+ +| [1, 2, 3, 4, 5, 6] | ++----------------------------------------------------+ +> select array_union([1, 2, 3, 4], [5, 6, 7, 8]); ++----------------------------------------------------+ +| array_union([1, 2, 3, 4], [5, 6, 7, 8]); | ++----------------------------------------------------+ +| [1, 2, 3, 4, 5, 6, 7, 8] | ++----------------------------------------------------+ +``` + +--- + +###### Aliases + +- list_union + +##### `array_except` + +Returns an array of the elements that appear in the first array but not in the second. + +``` +array_except(array1, array2) +``` + +###### Arguments + +- **array1**: Array expression. + Can be a constant, column, or function, and any combination of array operators. +- **array2**: Array expression. + Can be a constant, column, or function, and any combination of array operators. + +###### Example + +``` +> select array_except([1, 2, 3, 4], [5, 6, 3, 4]); ++----------------------------------------------------+ +| array_except([1, 2, 3, 4], [5, 6, 3, 4]); | ++----------------------------------------------------+ +| [1, 2] | ++----------------------------------------------------+ +> select array_except([1, 2, 3, 4], [3, 4, 5, 6]); ++----------------------------------------------------+ +| array_except([1, 2, 3, 4], [3, 4, 5, 6]); | ++----------------------------------------------------+ +| [1, 2] | ++----------------------------------------------------+ +``` + +--- + +###### Aliases + +- list_except + +##### `cardinality` + +Returns the total number of elements in the array. + +``` +cardinality(array) +``` + +###### Arguments + +- **array**: Array expression. + Can be a constant, column, or function, and any combination of array operators. + +###### Example + +``` +> select cardinality([[1, 2, 3, 4], [5, 6, 7, 8]]); ++--------------------------------------+ +| cardinality(List([1,2,3,4,5,6,7,8])) | ++--------------------------------------+ +| 8 | ++--------------------------------------+ +``` + +##### `empty` + +Returns 1 for an empty array or 0 for a non-empty array. + +``` +empty(array) +``` + +###### Arguments + +- **array**: Array expression. + Can be a constant, column, or function, and any combination of array operators. + +###### Example + +``` +> select empty([1]); ++------------------+ +| empty(List([1])) | ++------------------+ +| 0 | ++------------------+ +``` + +###### Aliases + +- array_empty, +- list_empty + +##### `generate_series` + +Similar to the range function, but it includes the upper bound. + +``` +generate_series(start, stop, step) +``` + +###### Arguments + +- **start**: start of the series. Ints, timestamps, dates or string types that can be coerced to Date32 are supported. +- **end**: end of the series (included). Type must be the same as start. +- **step**: increase by step (can not be 0). Steps less than a day are supported only for timestamp ranges. + +###### Example + +``` +> select generate_series(1,3); ++------------------------------------+ +| generate_series(Int64(1),Int64(3)) | ++------------------------------------+ +| [1, 2, 3] | ++------------------------------------+ +``` + +##### `list_any_value` + +_Alias of [array_any_value](#array-any-value)._ + +##### `list_append` + +_Alias of [array_append](#array-append)._ + +##### `list_cat` + +_Alias of [array_concat](#array-concat)._ + +##### `list_concat` + +_Alias of [array_concat](#array-concat)._ + +##### `list_dims` + +_Alias of [array_dims](#array-dims)._ + +##### `list_distance` + +_Alias of [array_distance](#array-distance)._ + +##### `list_distinct` + +_Alias of [array_distinct](#array-distinct)._ + +##### `list_element` + +_Alias of [array_element](#array-element)._ + +##### `list_empty` + +_Alias of [empty](#empty)._ + +##### `list_except` + +_Alias of [array_element](#array-except)._ + +##### `list_extract` + +_Alias of [array_element](#array-element)._ + +##### `list_has` + +_Alias of [array_has](#array-has)._ + +##### `list_has_all` + +_Alias of [array_has_all](#array-has-all)._ + +##### `list_has_any` + +_Alias of [array_has_any](#array-has-any)._ + +##### `list_indexof` + +_Alias of [array_position](#array-position)._ + +##### `list_intersect` + +_Alias of [array_position](#array-intersect)._ + +##### `list_join` + +_Alias of [array_to_string](#array-to-string)._ + +##### `list_length` + +_Alias of [array_length](#array-length)._ + +##### `list_ndims` + +_Alias of [array_ndims](#array-ndims)._ + +##### `list_prepend` + +_Alias of [array_prepend](#array-prepend)._ + +##### `list_pop_back` + +_Alias of [array_pop_back](#array-pop-back)._ + +##### `list_pop_front` + +_Alias of [array_pop_front](#array-pop-front)._ + +##### `list_position` + +_Alias of [array_position](#array-position)._ + +##### `list_positions` + +_Alias of [array_positions](#array-positions)._ + +##### `list_push_back` + +_Alias of [array_append](#array-append)._ + +##### `list_push_front` + +_Alias of [array_prepend](#array-prepend)._ + +##### `list_repeat` + +_Alias of [array_repeat](#array-repeat)._ + +##### `list_resize` + +_Alias of [array_resize](#array-resize)._ + +##### `list_remove` + +_Alias of [array_remove](#array-remove)._ + +##### `list_remove_n` + +_Alias of [array_remove_n](#array-remove-n)._ + +##### `list_remove_all` + +_Alias of [array_remove_all](#array-remove-all)._ + +##### `list_replace` + +_Alias of [array_replace](#array-replace)._ + +##### `list_replace_n` + +_Alias of [array_replace_n](#array-replace-n)._ + +##### `list_replace_all` + +_Alias of [array_replace_all](#array-replace-all)._ + +##### `list_reverse` + +_Alias of [array_reverse](#array-reverse)._ + +##### `list_slice` + +_Alias of [array_slice](#array-slice)._ + +##### `list_sort` + +_Alias of [array_sort](#array-sort)._ + +##### `list_to_string` + +_Alias of [array_to_string](#array-to-string)._ + +##### `list_union` + +_Alias of [array_union](#array-union)._ + +##### `make_array` + +Returns an Arrow array using the specified input expressions. + +``` +make_array(expression1[, ..., expression_n]) +``` + +##### `array_empty` + +_Alias of [empty](#empty)._ + +###### Arguments + +- **expression_n**: Expression to include in the output array. + Can be a constant, column, or function, and any combination of arithmetic or + string operators. + +###### Example + +``` +> select make_array(1, 2, 3, 4, 5); ++----------------------------------------------------------+ +| make_array(Int64(1),Int64(2),Int64(3),Int64(4),Int64(5)) | ++----------------------------------------------------------+ +| [1, 2, 3, 4, 5] | ++----------------------------------------------------------+ +``` + +###### Aliases + +- make_list + +##### `make_list` + +_Alias of [make_array](#make-array)._ + +##### `string_to_array` + +Splits a string in to an array of substrings based on a delimiter. Any substrings matching the optional `null_str` argument are replaced with NULL. +`SELECT string_to_array('abc##def', '##')` or `SELECT string_to_array('abc def', ' ', 'def')` + +``` +starts_with(str, delimiter[, null_str]) +``` + +###### Arguments + +- **str**: String expression to split. +- **delimiter**: Delimiter string to split on. +- **null_str**: Substring values to be replaced with `NULL` + +###### Aliases + +- string_to_list + +##### `string_to_list` + +_Alias of [string_to_array](#string-to-array)._ + +##### `trim_array` + +Removes the last n elements from the array. + +DEPRECATED: use `array_slice` instead! + +``` +trim_array(array, n) +``` + +###### Arguments + +- **array**: Array expression. + Can be a constant, column, or function, and any combination of array operators. +- **n**: Element to trim the array. + +##### `unnest` + +Transforms an array into rows. + +###### Arguments + +- **array**: Array expression to unnest. + Can be a constant, column, or function, and any combination of array operators. + +###### Examples + +``` +> select unnest(make_array(1, 2, 3, 4, 5)); ++------------------------------------------------------------------+ +| unnest(make_array(Int64(1),Int64(2),Int64(3),Int64(4),Int64(5))) | ++------------------------------------------------------------------+ +| 1 | +| 2 | +| 3 | +| 4 | +| 5 | ++------------------------------------------------------------------+ +``` + +``` +> select unnest(range(0, 10)); ++-----------------------------------+ +| unnest(range(Int64(0),Int64(10))) | ++-----------------------------------+ +| 0 | +| 1 | +| 2 | +| 3 | +| 4 | +| 5 | +| 6 | +| 7 | +| 8 | +| 9 | ++-----------------------------------+ +``` + +##### `range` + +Returns an Arrow array between start and stop with step. `SELECT range(2, 10, 3) -> [2, 5, 8]` or `SELECT range(DATE '1992-09-01', DATE '1993-03-01', INTERVAL '1' MONTH);` + +The range start..end contains all values with `start <= x < end`. It is empty if `start >= end`. + +Step can not be 0 (then the range will be nonsense.). + +Note that when the required range is a number, it accepts (stop), (start, stop), and (start, stop, step) as parameters, but when the required range is a date or timestamp, it must be 3 non-NULL parameters. +For example, + +``` +SELECT range(3); +SELECT range(1,5); +SELECT range(1,5,1); +``` + +are allowed in number ranges + +but in date and timestamp ranges, only + +``` +SELECT range(DATE '1992-09-01', DATE '1993-03-01', INTERVAL '1' MONTH); +SELECT range(TIMESTAMP '1992-09-01', TIMESTAMP '1993-03-01', INTERVAL '1' MONTH); +``` + +is allowed, and + +``` +SELECT range(DATE '1992-09-01', DATE '1993-03-01', NULL); +SELECT range(NULL, DATE '1993-03-01', INTERVAL '1' MONTH); +SELECT range(DATE '1992-09-01', NULL, INTERVAL '1' MONTH); +``` + +are not allowed + +###### Arguments + +- **start**: start of the range. Ints, timestamps, dates or string types that can be coerced to Date32 are supported. +- **end**: end of the range (not included). Type must be the same as start. +- **step**: increase by step (can not be 0). Steps less than a day are supported only for timestamp ranges. + +###### Aliases + +- generate_series + +### Struct Functions + +- [unnest](#unnest-struct) + +For more struct functions see the new documentation [`here`](https://datafusion.apache.org/user-guide/sql/scalar_functions_new.html) + +##### `unnest (struct)` + +Unwraps struct fields into columns. + +###### Arguments + +- **struct**: Object expression to unnest. + Can be a constant, column, or function, and any combination of object operators. + +###### Examples + +``` +> select * from foo; ++---------------------+ +| column1 | ++---------------------+ +| {a: 5, b: a string} | ++---------------------+ + +> select unnest(column1) from foo; ++-----------------------+-----------------------+ +| unnest(foo.column1).a | unnest(foo.column1).b | ++-----------------------+-----------------------+ +| 5 | a string | ++-----------------------+-----------------------+ +``` + +### Map Functions + +- [map](#map) +- [make_map](#make-map) +- [map_extract](#map-extract) +- [map_keys](#map-keys) +- [map_values](#map-values) + +##### `map` + +Returns an Arrow map with the specified key-value pairs. + +``` +map(key, value) +map(key: value) +``` + +###### Arguments + +- **key**: Expression to be used for key. + Can be a constant, column, or function, any combination of arithmetic or + string operators, or a named expression of previous listed. +- **value**: Expression to be used for value. + Can be a constant, column, or function, any combination of arithmetic or + string operators, or a named expression of previous listed. + +###### Example + +``` +SELECT MAP(['POST', 'HEAD', 'PATCH'], [41, 33, null]); +---- +{POST: 41, HEAD: 33, PATCH: } + +SELECT MAP([[1,2], [3,4]], ['a', 'b']); +---- +{[1, 2]: a, [3, 4]: b} + +SELECT MAP { 'a': 1, 'b': 2 }; +---- +{a: 1, b: 2} +``` + +##### `make_map` + +Returns an Arrow map with the specified key-value pairs. + +``` +make_map(key_1, value_1, ..., key_n, value_n) +``` + +###### Arguments + +- **key_n**: Expression to be used for key. + Can be a constant, column, or function, any combination of arithmetic or + string operators, or a named expression of previous listed. +- **value_n**: Expression to be used for value. + Can be a constant, column, or function, any combination of arithmetic or + string operators, or a named expression of previous listed. + +###### Example + +``` +SELECT MAKE_MAP('POST', 41, 'HEAD', 33, 'PATCH', null); +---- +{POST: 41, HEAD: 33, PATCH: } +``` + +##### `map_extract` + +Return a list containing the value for a given key or an empty list if the key is not contained in the map. + +``` +map_extract(map, key) +``` + +###### Arguments + +- `map`: Map expression. + Can be a constant, column, or function, and any combination of map operators. +- `key`: Key to extract from the map. + Can be a constant, column, or function, any combination of arithmetic or + string operators, or a named expression of previous listed. + +###### Example + +``` +SELECT map_extract(MAP {'a': 1, 'b': NULL, 'c': 3}, 'a'); +---- +[1] +``` + +###### Aliases + +- element_at + +##### `map_keys` + +Return a list of all keys in the map. + +``` +map_keys(map) +``` + +###### Arguments + +- `map`: Map expression. + Can be a constant, column, or function, and any combination of map operators. + +###### Example + +``` +SELECT map_keys(MAP {'a': 1, 'b': NULL, 'c': 3}); +---- +[a, b, c] + +select map_keys(map([100, 5], [42,43])); +---- +[100, 5] +``` + +##### `map_values` + +Return a list of all values in the map. + +``` +map_values(map) +``` + +###### Arguments + +- `map`: Map expression. + Can be a constant, column, or function, and any combination of map operators. + +###### Example + +``` +SELECT map_values(MAP {'a': 1, 'b': NULL, 'c': 3}); +---- +[1, , 3] + +select map_values(map([100, 5], [42,43])); +---- +[42, 43] +``` + +### Other Functions + +See the new documentation [`here`](https://datafusion.apache.org/user-guide/sql/scalar_functions_new.html) + + + + +## Scalar Functions (NEW) + +Note: this documentation is in the process of being migrated to be [automatically created from the codebase]. +Please see the [Scalar Functions (old)](#aggregate-functions) page for +the rest of the documentation. + +### Math Functions + +- [log](#log) + +##### `log` + +Returns the base-x logarithm of a number. Can either provide a specified base, or if omitted then takes the base-10 of a number. + +``` +log(base, numeric_expression) +log(numeric_expression) +``` + +###### Arguments + +- **base**: Base numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. +- **numeric_expression**: Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators. + +### Conditional Functions + +- [coalesce](#coalesce) +- [ifnull](#ifnull) +- [nullif](#nullif) +- [nvl](#nvl) +- [nvl2](#nvl2) + +##### `coalesce` + +Returns the first of its arguments that is not _null_. Returns _null_ if all arguments are _null_. This function is often used to substitute a default value for _null_ values. + +``` +coalesce(expression1[, ..., expression_n]) +``` + +###### Arguments + +- **expression1, expression_n**: Expression to use if previous expressions are _null_. Can be a constant, column, or function, and any combination of arithmetic operators. Pass as many expression arguments as necessary. + +###### Example + +```sql +> select coalesce(null, null, 'datafusion'); ++----------------------------------------+ +| coalesce(NULL,NULL,Utf8("datafusion")) | ++----------------------------------------+ +| datafusion | ++----------------------------------------+ +``` + +##### `ifnull` + +_Alias of [nvl](#nvl)._ + +##### `nullif` + +Returns _null_ if _expression1_ equals _expression2_; otherwise it returns _expression1_. +This can be used to perform the inverse operation of [`coalesce`](#coalesce). + +``` +nullif(expression1, expression2) +``` + +###### Arguments + +- **expression1**: Expression to compare and return if equal to expression2. Can be a constant, column, or function, and any combination of operators. +- **expression2**: Expression to compare to expression1. Can be a constant, column, or function, and any combination of operators. + +###### Example + +```sql +> select nullif('datafusion', 'data'); ++-----------------------------------------+ +| nullif(Utf8("datafusion"),Utf8("data")) | ++-----------------------------------------+ +| datafusion | ++-----------------------------------------+ +> select nullif('datafusion', 'datafusion'); ++-----------------------------------------------+ +| nullif(Utf8("datafusion"),Utf8("datafusion")) | ++-----------------------------------------------+ +| | ++-----------------------------------------------+ +``` + +##### `nvl` + +Returns _expression2_ if _expression1_ is NULL otherwise it returns _expression1_. + +``` +nvl(expression1, expression2) +``` + +###### Arguments + +- **expression1**: Expression to return if not null. Can be a constant, column, or function, and any combination of operators. +- **expression2**: Expression to return if expr1 is null. Can be a constant, column, or function, and any combination of operators. + +###### Example + +```sql +> select nvl(null, 'a'); ++---------------------+ +| nvl(NULL,Utf8("a")) | ++---------------------+ +| a | ++---------------------+\ +> select nvl('b', 'a'); ++--------------------------+ +| nvl(Utf8("b"),Utf8("a")) | ++--------------------------+ +| b | ++--------------------------+ +``` + +###### Aliases + +- ifnull + +##### `nvl2` + +Returns _expression2_ if _expression1_ is not NULL; otherwise it returns _expression3_. + +``` +nvl2(expression1, expression2, expression3) +``` + +###### Arguments + +- **expression1**: Expression to test for null. Can be a constant, column, or function, and any combination of operators. +- **expression2**: Expression to return if expr1 is not null. Can be a constant, column, or function, and any combination of operators. +- **expression3**: Expression to return if expr1 is null. Can be a constant, column, or function, and any combination of operators. + +###### Example + +```sql +> select nvl2(null, 'a', 'b'); ++--------------------------------+ +| nvl2(NULL,Utf8("a"),Utf8("b")) | ++--------------------------------+ +| b | ++--------------------------------+ +> select nvl2('data', 'a', 'b'); ++----------------------------------------+ +| nvl2(Utf8("data"),Utf8("a"),Utf8("b")) | ++----------------------------------------+ +| a | ++----------------------------------------+ +``` + +### String Functions + +- [ascii](#ascii) +- [bit_length](#bit-length) +- [btrim](#btrim) +- [char_length](#char-length) +- [character_length](#character-length) +- [chr](#chr) +- [concat](#concat) +- [concat_ws](#concat-ws) +- [contains](#contains) +- [ends_with](#ends-with) +- [find_in_set](#find-in-set) +- [initcap](#initcap) +- [instr](#instr) +- [left](#left) +- [length](#length) +- [levenshtein](#levenshtein) +- [lower](#lower) +- [lpad](#lpad) +- [ltrim](#ltrim) +- [octet_length](#octet-length) +- [position](#position) +- [repeat](#repeat) +- [replace](#replace) +- [reverse](#reverse) +- [right](#right) +- [rpad](#rpad) +- [rtrim](#rtrim) +- [split_part](#split-part) +- [starts_with](#starts-with) +- [strpos](#strpos) +- [substr](#substr) +- [substr_index](#substr-index) +- [substring](#substring) +- [substring_index](#substring-index) +- [to_hex](#to-hex) +- [translate](#translate) +- [trim](#trim) +- [upper](#upper) +- [uuid](#uuid) + +##### `ascii` + +Returns the Unicode character code of the first character in a string. + +``` +ascii(str) +``` + +###### Arguments + +- **str**: String expression to operate on. Can be a constant, column, or function, and any combination of operators. + +###### Example + +```sql +> select ascii('abc'); ++--------------------+ +| ascii(Utf8("abc")) | ++--------------------+ +| 97 | ++--------------------+ +> select ascii('🚀'); ++-------------------+ +| ascii(Utf8("🚀")) | ++-------------------+ +| 128640 | ++-------------------+ +``` + +**Related functions**: + +- [chr](#chr) + +##### `bit_length` + +Returns the bit length of a string. + +``` +bit_length(str) +``` + +###### Arguments + +- **str**: String expression to operate on. Can be a constant, column, or function, and any combination of operators. + +###### Example + +```sql +> select bit_length('datafusion'); ++--------------------------------+ +| bit_length(Utf8("datafusion")) | ++--------------------------------+ +| 80 | ++--------------------------------+ +``` + +**Related functions**: + +- [length](#length) +- [octet_length](#octet-length) + +##### `btrim` + +Trims the specified trim string from the start and end of a string. If no trim string is provided, all whitespace is removed from the start and end of the input string. + +``` +btrim(str[, trim_str]) +``` + +###### Arguments + +- **str**: String expression to operate on. Can be a constant, column, or function, and any combination of operators. +- **trim_str**: String expression to operate on. Can be a constant, column, or function, and any combination of operators. _Default is whitespace characters._ + +###### Example + +```sql +> select btrim('__datafusion____', '_'); ++-------------------------------------------+ +| btrim(Utf8("__datafusion____"),Utf8("_")) | ++-------------------------------------------+ +| datafusion | ++-------------------------------------------+ +``` + +###### Aliases + +- trim + +**Related functions**: + +- [ltrim](#ltrim) +- [rtrim](#rtrim) + +##### `char_length` + +_Alias of [character_length](#character-length)._ + +##### `character_length` + +Returns the number of characters in a string. + +``` +character_length(str) +``` + +###### Arguments + +- **str**: String expression to operate on. Can be a constant, column, or function, and any combination of operators. + +###### Example + +```sql +> select character_length('Ångström'); ++------------------------------------+ +| character_length(Utf8("Ångström")) | ++------------------------------------+ +| 8 | ++------------------------------------+ +``` + +###### Aliases + +- length +- char_length + +**Related functions**: + +- [bit_length](#bit-length) +- [octet_length](#octet-length) + +##### `chr` + +Returns the character with the specified ASCII or Unicode code value. + +``` +chr(expression) +``` + +###### Arguments + +- **expression**: String expression to operate on. Can be a constant, column, or function, and any combination of operators. + +###### Example + +```sql +> select chr(128640); ++--------------------+ +| chr(Int64(128640)) | ++--------------------+ +| 🚀 | ++--------------------+ +``` + +**Related functions**: + +- [ascii](#ascii) + +##### `concat` + +Concatenates multiple strings together. + +``` +concat(str[, ..., str_n]) +``` + +###### Arguments + +- **str**: String expression to operate on. Can be a constant, column, or function, and any combination of operators. +- **str_n**: Subsequent string expressions to concatenate. + +###### Example + +```sql +> select concat('data', 'f', 'us', 'ion'); ++-------------------------------------------------------+ +| concat(Utf8("data"),Utf8("f"),Utf8("us"),Utf8("ion")) | ++-------------------------------------------------------+ +| datafusion | ++-------------------------------------------------------+ +``` + +**Related functions**: + +- [concat_ws](#concat-ws) + +##### `concat_ws` + +Concatenates multiple strings together with a specified separator. + +``` +concat_ws(separator, str[, ..., str_n]) +``` + +###### Arguments + +- **separator**: Separator to insert between concatenated strings. +- **str**: String expression to operate on. Can be a constant, column, or function, and any combination of operators. +- **str_n**: Subsequent string expressions to concatenate. expression to operate on. Can be a constant, column, or function, and any combination of operators. + +###### Example + +```sql +> select concat_ws('_', 'data', 'fusion'); ++--------------------------------------------------+ +| concat_ws(Utf8("_"),Utf8("data"),Utf8("fusion")) | ++--------------------------------------------------+ +| data_fusion | ++--------------------------------------------------+ +``` + +**Related functions**: + +- [concat](#concat) + +##### `contains` + +Return true if search_str is found within string (case-sensitive). + +``` +contains(str, search_str) +``` + +###### Arguments + +- **str**: String expression to operate on. Can be a constant, column, or function, and any combination of operators. +- **search_str**: The string to search for in str. + +###### Example + +```sql +> select contains('the quick brown fox', 'row'); ++---------------------------------------------------+ +| contains(Utf8("the quick brown fox"),Utf8("row")) | ++---------------------------------------------------+ +| true | ++---------------------------------------------------+ +``` + +##### `ends_with` + +Tests if a string ends with a substring. + +``` +ends_with(str, substr) +``` + +###### Arguments + +- **str**: String expression to operate on. Can be a constant, column, or function, and any combination of operators. +- **substr**: Substring to test for. + +###### Example + +```sql +> select ends_with('datafusion', 'soin'); ++--------------------------------------------+ +| ends_with(Utf8("datafusion"),Utf8("soin")) | ++--------------------------------------------+ +| false | ++--------------------------------------------+ +> select ends_with('datafusion', 'sion'); ++--------------------------------------------+ +| ends_with(Utf8("datafusion"),Utf8("sion")) | ++--------------------------------------------+ +| true | ++--------------------------------------------+ +``` + +##### `find_in_set` + +Returns a value in the range of 1 to N if the string str is in the string list strlist consisting of N substrings. + +``` +find_in_set(str, strlist) +``` + +###### Arguments + +- **str**: String expression to find in strlist. +- **strlist**: A string list is a string composed of substrings separated by , characters. + +###### Example + +```sql +> select find_in_set('b', 'a,b,c,d'); ++----------------------------------------+ +| find_in_set(Utf8("b"),Utf8("a,b,c,d")) | ++----------------------------------------+ +| 2 | ++----------------------------------------+ +``` + +##### `initcap` + +Capitalizes the first character in each word in the input string. Words are delimited by non-alphanumeric characters. + +``` +initcap(str) +``` + +###### Arguments + +- **str**: String expression to operate on. Can be a constant, column, or function, and any combination of operators. + +###### Example + +```sql +> select initcap('apache datafusion'); ++------------------------------------+ +| initcap(Utf8("apache datafusion")) | ++------------------------------------+ +| Apache Datafusion | ++------------------------------------+ +``` + +**Related functions**: + +- [lower](#lower) +- [upper](#upper) + +##### `instr` + +_Alias of [strpos](#strpos)._ + +##### `left` + +Returns a specified number of characters from the left side of a string. + +``` +left(str, n) +``` + +###### Arguments + +- **str**: String expression to operate on. Can be a constant, column, or function, and any combination of operators. +- **n**: Number of characters to return. + +###### Example + +```sql +> select left('datafusion', 4); ++-----------------------------------+ +| left(Utf8("datafusion"),Int64(4)) | ++-----------------------------------+ +| data | ++-----------------------------------+ +``` + +**Related functions**: + +- [right](#right) + +##### `length` + +_Alias of [character_length](#character-length)._ + +##### `levenshtein` + +Returns the [`Levenshtein distance`](https://en.wikipedia.org/wiki/Levenshtein_distance) between the two given strings. + +``` +levenshtein(str1, str2) +``` + +###### Arguments + +- **str1**: String expression to compute Levenshtein distance with str2. +- **str2**: String expression to compute Levenshtein distance with str1. + +###### Example + +```sql +> select levenshtein('kitten', 'sitting'); ++---------------------------------------------+ +| levenshtein(Utf8("kitten"),Utf8("sitting")) | ++---------------------------------------------+ +| 3 | ++---------------------------------------------+ +``` + +##### `lower` + +Converts a string to lower-case. + +``` +lower(str) +``` + +###### Arguments + +- **str**: String expression to operate on. Can be a constant, column, or function, and any combination of operators. + +###### Example + +```sql +> select lower('Ångström'); ++-------------------------+ +| lower(Utf8("Ångström")) | ++-------------------------+ +| ångström | ++-------------------------+ +``` + +**Related functions**: + +- [initcap](#initcap) +- [upper](#upper) + +##### `lpad` + +Pads the left side of a string with another string to a specified string length. + +``` +lpad(str, n[, padding_str]) +``` + +###### Arguments + +- **str**: String expression to operate on. Can be a constant, column, or function, and any combination of operators. +- **n**: String length to pad to. +- **padding_str**: Optional string expression to pad with. Can be a constant, column, or function, and any combination of string operators. _Default is a space._ + +###### Example + +```sql +> select lpad('Dolly', 10, 'hello'); ++---------------------------------------------+ +| lpad(Utf8("Dolly"),Int64(10),Utf8("hello")) | ++---------------------------------------------+ +| helloDolly | ++---------------------------------------------+ +``` + +**Related functions**: + +- [rpad](#rpad) + +##### `ltrim` + +Trims the specified trim string from the beginning of a string. If no trim string is provided, all whitespace is removed from the start of the input string. + +``` +ltrim(str[, trim_str]) +``` + +###### Arguments + +- **str**: String expression to operate on. Can be a constant, column, or function, and any combination of operators. +- **trim_str**: String expression to trim from the beginning of the input string. Can be a constant, column, or function, and any combination of arithmetic operators. _Default is whitespace characters._ + +###### Example + +```sql +> select ltrim(' datafusion '); ++-------------------------------+ +| ltrim(Utf8(" datafusion ")) | ++-------------------------------+ +| datafusion | ++-------------------------------+ +> select ltrim('___datafusion___', '_'); ++-------------------------------------------+ +| ltrim(Utf8("___datafusion___"),Utf8("_")) | ++-------------------------------------------+ +| datafusion___ | ++-------------------------------------------+ +``` + +**Related functions**: + +- [btrim](#btrim) +- [rtrim](#rtrim) + +##### `octet_length` + +Returns the length of a string in bytes. + +``` +octet_length(str) +``` + +###### Arguments + +- **str**: String expression to operate on. Can be a constant, column, or function, and any combination of operators. + +###### Example + +```sql +> select octet_length('Ångström'); ++--------------------------------+ +| octet_length(Utf8("Ångström")) | ++--------------------------------+ +| 10 | ++--------------------------------+ +``` + +**Related functions**: + +- [bit_length](#bit-length) +- [length](#length) + +##### `position` + +_Alias of [strpos](#strpos)._ + +##### `repeat` + +Returns a string with an input string repeated a specified number. + +``` +repeat(str, n) +``` + +###### Arguments + +- **str**: String expression to operate on. Can be a constant, column, or function, and any combination of operators. +- **n**: Number of times to repeat the input string. + +###### Example + +```sql +> select repeat('data', 3); ++-------------------------------+ +| repeat(Utf8("data"),Int64(3)) | ++-------------------------------+ +| datadatadata | ++-------------------------------+ +``` + +##### `replace` + +Replaces all occurrences of a specified substring in a string with a new substring. + +``` +replace(str, substr, replacement) +``` + +###### Arguments + +- **str**: String expression to operate on. Can be a constant, column, or function, and any combination of operators. +- **substr**: Substring expression to replace in the input string. Substring expression expression to operate on. Can be a constant, column, or function, and any combination of operators. +- **replacement**: Replacement substring expression to operate on. Can be a constant, column, or function, and any combination of operators. + +###### Example + +```sql +> select replace('ABabbaBA', 'ab', 'cd'); ++-------------------------------------------------+ +| replace(Utf8("ABabbaBA"),Utf8("ab"),Utf8("cd")) | ++-------------------------------------------------+ +| ABcdbaBA | ++-------------------------------------------------+ +``` + +##### `reverse` + +Reverses the character order of a string. + +``` +reverse(str) +``` + +###### Arguments + +- **str**: String expression to operate on. Can be a constant, column, or function, and any combination of operators. + +###### Example + +```sql +> select reverse('datafusion'); ++-----------------------------+ +| reverse(Utf8("datafusion")) | ++-----------------------------+ +| noisufatad | ++-----------------------------+ +``` + +##### `right` + +Returns a specified number of characters from the right side of a string. + +``` +right(str, n) +``` + +###### Arguments + +- **str**: String expression to operate on. Can be a constant, column, or function, and any combination of operators. +- **n**: Number of characters to return + +###### Example + +```sql +> select right('datafusion', 6); ++------------------------------------+ +| right(Utf8("datafusion"),Int64(6)) | ++------------------------------------+ +| fusion | ++------------------------------------+ +``` + +**Related functions**: + +- [left](#left) + +##### `rpad` + +Pads the right side of a string with another string to a specified string length. + +``` +rpad(str, n[, padding_str]) +``` + +###### Arguments + +- **str**: String expression to operate on. Can be a constant, column, or function, and any combination of operators. +- **n**: String length to pad to. +- **padding_str**: String expression to pad with. Can be a constant, column, or function, and any combination of string operators. _Default is a space._ + +###### Example + +```sql +> select rpad('datafusion', 20, '_-'); ++-----------------------------------------------+ +| rpad(Utf8("datafusion"),Int64(20),Utf8("_-")) | ++-----------------------------------------------+ +| datafusion_-_-_-_-_- | ++-----------------------------------------------+ +``` + +**Related functions**: + +- [lpad](#lpad) + +##### `rtrim` + +Trims the specified trim string from the end of a string. If no trim string is provided, all whitespace is removed from the end of the input string. + +``` +rtrim(str[, trim_str]) +``` + +###### Arguments + +- **str**: String expression to operate on. Can be a constant, column, or function, and any combination of operators. +- **trim_str**: String expression to trim from the end of the input string. Can be a constant, column, or function, and any combination of arithmetic operators. _Default is whitespace characters._ + +###### Example + +```sql +> select rtrim(' datafusion '); ++-------------------------------+ +| rtrim(Utf8(" datafusion ")) | ++-------------------------------+ +| datafusion | ++-------------------------------+ +> select rtrim('___datafusion___', '_'); ++-------------------------------------------+ +| rtrim(Utf8("___datafusion___"),Utf8("_")) | ++-------------------------------------------+ +| ___datafusion | ++-------------------------------------------+ +``` + +**Related functions**: + +- [btrim](#btrim) +- [ltrim](#ltrim) + +##### `split_part` + +Splits a string based on a specified delimiter and returns the substring in the specified position. + +``` +split_part(str, delimiter, pos) +``` + +###### Arguments + +- **str**: String expression to operate on. Can be a constant, column, or function, and any combination of operators. +- **delimiter**: String or character to split on. +- **pos**: Position of the part to return. + +###### Example + +```sql +> select split_part('1.2.3.4.5', '.', 3); ++--------------------------------------------------+ +| split_part(Utf8("1.2.3.4.5"),Utf8("."),Int64(3)) | ++--------------------------------------------------+ +| 3 | ++--------------------------------------------------+ +``` + +##### `starts_with` + +Tests if a string starts with a substring. + +``` +starts_with(str, substr) +``` + +###### Arguments + +- **str**: String expression to operate on. Can be a constant, column, or function, and any combination of operators. +- **substr**: Substring to test for. + +###### Example + +```sql +> select starts_with('datafusion','data'); ++----------------------------------------------+ +| starts_with(Utf8("datafusion"),Utf8("data")) | ++----------------------------------------------+ +| true | ++----------------------------------------------+ +``` + +##### `strpos` + +Returns the starting position of a specified substring in a string. Positions begin at 1. If the substring does not exist in the string, the function returns 0. + +``` +strpos(str, substr) +``` + +###### Arguments + +- **str**: String expression to operate on. Can be a constant, column, or function, and any combination of operators. +- **substr**: Substring expression to search for. + +###### Example + +```sql +> select strpos('datafusion', 'fus'); ++----------------------------------------+ +| strpos(Utf8("datafusion"),Utf8("fus")) | ++----------------------------------------+ +| 5 | ++----------------------------------------+ +``` + +###### Aliases + +- instr +- position + +##### `substr` + +Extracts a substring of a specified number of characters from a specific starting position in a string. + +``` +substr(str, start_pos[, length]) +``` + +###### Arguments + +- **str**: String expression to operate on. Can be a constant, column, or function, and any combination of operators. +- **start_pos**: Character position to start the substring at. The first character in the string has a position of 1. +- **length**: Number of characters to extract. If not specified, returns the rest of the string after the start position. + +###### Example + +```sql +> select substr('datafusion', 5, 3); ++----------------------------------------------+ +| substr(Utf8("datafusion"),Int64(5),Int64(3)) | ++----------------------------------------------+ +| fus | ++----------------------------------------------+ +``` + +###### Aliases + +- substring + +##### `substr_index` + +Returns the substring from str before count occurrences of the delimiter delim. +If count is positive, everything to the left of the final delimiter (counting from the left) is returned. +If count is negative, everything to the right of the final delimiter (counting from the right) is returned. + +``` +substr_index(str, delim, count) +``` + +###### Arguments + +- **str**: String expression to operate on. Can be a constant, column, or function, and any combination of operators. +- **delim**: The string to find in str to split str. +- **count**: The number of times to search for the delimiter. Can be either a positive or negative number. + +###### Example + +```sql +> select substr_index('www.apache.org', '.', 1); ++---------------------------------------------------------+ +| substr_index(Utf8("www.apache.org"),Utf8("."),Int64(1)) | ++---------------------------------------------------------+ +| www | ++---------------------------------------------------------+ +> select substr_index('www.apache.org', '.', -1); ++----------------------------------------------------------+ +| substr_index(Utf8("www.apache.org"),Utf8("."),Int64(-1)) | ++----------------------------------------------------------+ +| org | ++----------------------------------------------------------+ +``` + +###### Aliases + +- substring_index + +##### `substring` + +_Alias of [substr](#substr)._ + +##### `substring_index` + +_Alias of [substr_index](#substr-index)._ + +##### `to_hex` + +Converts an integer to a hexadecimal string. + +``` +to_hex(int) +``` + +###### Arguments + +- **int**: Integer expression to operate on. Can be a constant, column, or function, and any combination of operators. + +###### Example + +```sql +> select to_hex(12345689); ++-------------------------+ +| to_hex(Int64(12345689)) | ++-------------------------+ +| bc6159 | ++-------------------------+ +``` + +##### `translate` + +Translates characters in a string to specified translation characters. + +``` +translate(str, chars, translation) +``` + +###### Arguments + +- **str**: String expression to operate on. Can be a constant, column, or function, and any combination of operators. +- **chars**: Characters to translate. +- **translation**: Translation characters. Translation characters replace only characters at the same position in the **chars** string. + +###### Example + +```sql +> select translate('twice', 'wic', 'her'); ++--------------------------------------------------+ +| translate(Utf8("twice"),Utf8("wic"),Utf8("her")) | ++--------------------------------------------------+ +| there | ++--------------------------------------------------+ +``` + +##### `trim` + +_Alias of [btrim](#btrim)._ + +##### `upper` + +Converts a string to upper-case. + +``` +upper(str) +``` + +###### Arguments + +- **str**: String expression to operate on. Can be a constant, column, or function, and any combination of operators. + +###### Example + +```sql +> select upper('dataFusion'); ++---------------------------+ +| upper(Utf8("dataFusion")) | ++---------------------------+ +| DATAFUSION | ++---------------------------+ +``` + +**Related functions**: + +- [initcap](#initcap) +- [lower](#lower) + +##### `uuid` + +Returns [`UUID v4`]() string value which is unique per row. + +``` +uuid() +``` + +###### Example + +```sql +> select uuid(); ++--------------------------------------+ +| uuid() | ++--------------------------------------+ +| 6ec17ef8-1934-41cc-8d59-d0c8f9eea1f0 | ++--------------------------------------+ +``` + +### Binary String Functions + +- [decode](#decode) +- [encode](#encode) + +##### `decode` + +Decode binary data from textual representation in string. + +``` +decode(expression, format) +``` + +###### Arguments + +- **expression**: Expression containing encoded string data +- **format**: Same arguments as [encode](#encode) + +**Related functions**: + +- [encode](#encode) + +##### `encode` + +Encode binary data into a textual representation. + +``` +encode(expression, format) +``` + +###### Arguments + +- **expression**: Expression containing string or binary data +- **format**: Supported formats are: `base64`, `hex` + +**Related functions**: + +- [decode](#decode) + +### Regular Expression Functions + +Apache DataFusion uses a [PCRE-like](https://en.wikibooks.org/wiki/Regular_Expressions/Perl-Compatible_Regular_Expressions) +regular expression [syntax](https://docs.rs/regex/latest/regex/#syntax) +(minus support for several features including look-around and backreferences). +The following regular expression functions are supported: + +- [regexp_like](#regexp-like) +- [regexp_match](#regexp-match) +- [regexp_replace](#regexp-replace) + +##### `regexp_like` + +Returns true if a [regular expression](https://docs.rs/regex/latest/regex/#syntax) has at least one match in a string, false otherwise. + +``` +regexp_like(str, regexp[, flags]) +``` + +###### Arguments + +- **str**: String expression to operate on. Can be a constant, column, or function, and any combination of operators. +- **regexp**: Regular expression to operate on. Can be a constant, column, or function, and any combination of operators. +- **flags**: Optional regular expression flags that control the behavior of the regular expression. The following flags are supported: + - **i**: case-insensitive: letters match both upper and lower case + - **m**: multi-line mode: ^ and $ match begin/end of line + - **s**: allow . to match \n + - **R**: enables CRLF mode: when multi-line mode is enabled, \r\n is used + - **U**: swap the meaning of x* and x*? + +###### Example + +```sql +select regexp_like('Köln', '[a-zA-Z]ö[a-zA-Z]{2}'); ++--------------------------------------------------------+ +| regexp_like(Utf8("Köln"),Utf8("[a-zA-Z]ö[a-zA-Z]{2}")) | ++--------------------------------------------------------+ +| true | ++--------------------------------------------------------+ +SELECT regexp_like('aBc', '(b|d)', 'i'); ++--------------------------------------------------+ +| regexp_like(Utf8("aBc"),Utf8("(b|d)"),Utf8("i")) | ++--------------------------------------------------+ +| true | ++--------------------------------------------------+ +``` + +Additional examples can be found [here](https://github.com/apache/datafusion/blob/main/datafusion-examples/examples/regexp.rs) + +##### `regexp_match` + +Returns a list of [regular expression](https://docs.rs/regex/latest/regex/#syntax) matches in a string. + +``` +regexp_match(str, regexp[, flags]) +``` + +###### Arguments + +- **str**: String expression to operate on. Can be a constant, column, or function, and any combination of operators. +- **regexp**: Regular expression to match against. + Can be a constant, column, or function. +- **flags**: Optional regular expression flags that control the behavior of the regular expression. The following flags are supported: + - **i**: case-insensitive: letters match both upper and lower case + - **m**: multi-line mode: ^ and $ match begin/end of line + - **s**: allow . to match \n + - **R**: enables CRLF mode: when multi-line mode is enabled, \r\n is used + - **U**: swap the meaning of x* and x*? + +###### Example + +```sql + > select regexp_match('Köln', '[a-zA-Z]ö[a-zA-Z]{2}'); + +---------------------------------------------------------+ + | regexp_match(Utf8("Köln"),Utf8("[a-zA-Z]ö[a-zA-Z]{2}")) | + +---------------------------------------------------------+ + | [Köln] | + +---------------------------------------------------------+ + SELECT regexp_match('aBc', '(b|d)', 'i'); + +---------------------------------------------------+ + | regexp_match(Utf8("aBc"),Utf8("(b|d)"),Utf8("i")) | + +---------------------------------------------------+ + | [B] | + +---------------------------------------------------+ +``` + +Additional examples can be found [here](https://github.com/apache/datafusion/blob/main/datafusion-examples/examples/regexp.rs) + +##### `regexp_replace` + +Replaces substrings in a string that match a [regular expression](https://docs.rs/regex/latest/regex/#syntax). + +``` +regexp_replace(str, regexp, replacement[, flags]) +``` + +###### Arguments + +- **str**: String expression to operate on. Can be a constant, column, or function, and any combination of operators. +- **regexp**: Regular expression to match against. + Can be a constant, column, or function. +- **replacement**: Replacement string expression to operate on. Can be a constant, column, or function, and any combination of operators. +- **flags**: Optional regular expression flags that control the behavior of the regular expression. The following flags are supported: +- **g**: (global) Search globally and don't return after the first match +- **i**: case-insensitive: letters match both upper and lower case +- **m**: multi-line mode: ^ and $ match begin/end of line +- **s**: allow . to match \n +- **R**: enables CRLF mode: when multi-line mode is enabled, \r\n is used +- **U**: swap the meaning of x* and x*? + +###### Example + +```sql +> select regexp_replace('foobarbaz', 'b(..)', 'X\\1Y', 'g'); ++------------------------------------------------------------------------+ +| regexp_replace(Utf8("foobarbaz"),Utf8("b(..)"),Utf8("X\1Y"),Utf8("g")) | ++------------------------------------------------------------------------+ +| fooXarYXazY | ++------------------------------------------------------------------------+ +SELECT regexp_replace('aBc', '(b|d)', 'Ab\\1a', 'i'); ++-------------------------------------------------------------------+ +| regexp_replace(Utf8("aBc"),Utf8("(b|d)"),Utf8("Ab\1a"),Utf8("i")) | ++-------------------------------------------------------------------+ +| aAbBac | ++-------------------------------------------------------------------+ +``` + +Additional examples can be found [here](https://github.com/apache/datafusion/blob/main/datafusion-examples/examples/regexp.rs) + +### Time and Date Functions + +- [to_date](#to-date) + +##### `to_date` + +Converts a value to a date (`YYYY-MM-DD`). +Supports strings, integer and double types as input. +Strings are parsed as YYYY-MM-DD (e.g. '2023-07-20') if no [Chrono format](https://docs.rs/chrono/latest/chrono/format/strftime/index.html)s are provided. +Integers and doubles are interpreted as days since the unix epoch (`1970-01-01T00:00:00Z`). +Returns the corresponding date. + +Note: `to_date` returns Date32, which represents its values as the number of days since unix epoch(`1970-01-01`) stored as signed 32 bit value. The largest supported date value is `9999-12-31`. + +``` +to_date('2017-05-31', '%Y-%m-%d') +``` + +###### Arguments + +- **expression**: String expression to operate on. Can be a constant, column, or function, and any combination of operators. +- **format_n**: Optional [Chrono format](https://docs.rs/chrono/latest/chrono/format/strftime/index.html) strings to use to parse the expression. Formats will be tried in the order + they appear with the first successful one being returned. If none of the formats successfully parse the expression + an error will be returned. + +###### Example + +```sql +> select to_date('2023-01-31'); ++-----------------------------+ +| to_date(Utf8("2023-01-31")) | ++-----------------------------+ +| 2023-01-31 | ++-----------------------------+ +> select to_date('2023/01/31', '%Y-%m-%d', '%Y/%m/%d'); ++---------------------------------------------------------------+ +| to_date(Utf8("2023/01/31"),Utf8("%Y-%m-%d"),Utf8("%Y/%m/%d")) | ++---------------------------------------------------------------+ +| 2023-01-31 | ++---------------------------------------------------------------+ +``` + +Additional examples can be found [here](https://github.com/apache/datafusion/blob/main/datafusion-examples/examples/to_date.rs) + +### Struct Functions + +- [named_struct](#named-struct) +- [row](#row) +- [struct](#struct) + +##### `named_struct` + +Returns an Arrow struct using the specified name and input expressions pairs. + +``` +named_struct(expression1_name, expression1_input[, ..., expression_n_name, expression_n_input]) +``` + +###### Arguments + +- **expression_n_name**: Name of the column field. Must be a constant string. +- **expression_n_input**: Expression to include in the output struct. Can be a constant, column, or function, and any combination of arithmetic or string operators. + +###### Example + +For example, this query converts two columns `a` and `b` to a single column with +a struct type of fields `field_a` and `field_b`: + +```sql +> select * from t; ++---+---+ +| a | b | ++---+---+ +| 1 | 2 | +| 3 | 4 | ++---+---+ +> select named_struct('field_a', a, 'field_b', b) from t; ++-------------------------------------------------------+ +| named_struct(Utf8("field_a"),t.a,Utf8("field_b"),t.b) | ++-------------------------------------------------------+ +| {field_a: 1, field_b: 2} | +| {field_a: 3, field_b: 4} | ++-------------------------------------------------------+ +``` + +##### `row` + +_Alias of [struct](#struct)._ + +##### `struct` + +Returns an Arrow struct using the specified input expressions optionally named. +Fields in the returned struct use the optional name or the `cN` naming convention. +For example: `c0`, `c1`, `c2`, etc. + +``` +struct(expression1[, ..., expression_n]) +``` + +###### Arguments + +- **expression1, expression_n**: Expression to include in the output struct. Can be a constant, column, or function, any combination of arithmetic or string operators. + +###### Example + +For example, this query converts two columns `a` and `b` to a single column with +a struct type of fields `field_a` and `c1`: + +```sql +> select * from t; ++---+---+ +| a | b | ++---+---+ +| 1 | 2 | +| 3 | 4 | ++---+---+ + +-- use default names `c0`, `c1` +> select struct(a, b) from t; ++-----------------+ +| struct(t.a,t.b) | ++-----------------+ +| {c0: 1, c1: 2} | +| {c0: 3, c1: 4} | ++-----------------+ + +-- name the first field `field_a` +select struct(a as field_a, b) from t; ++--------------------------------------------------+ +| named_struct(Utf8("field_a"),t.a,Utf8("c1"),t.b) | ++--------------------------------------------------+ +| {field_a: 1, c1: 2} | +| {field_a: 3, c1: 4} | ++--------------------------------------------------+ +``` + +###### Aliases + +- row + +### Hashing Functions + +- [digest](#digest) +- [md5](#md5) +- [sha224](#sha224) +- [sha256](#sha256) +- [sha384](#sha384) +- [sha512](#sha512) + +##### `digest` + +Computes the binary hash of an expression using the specified algorithm. + +``` +digest(expression, algorithm) +``` + +###### Arguments + +- **expression**: String expression to operate on. Can be a constant, column, or function, and any combination of operators. +- **algorithm**: String expression specifying algorithm to use. Must be one of: +- md5 +- sha224 +- sha256 +- sha384 +- sha512 +- blake2s +- blake2b +- blake3 + +###### Example + +```sql +> select digest('foo', 'sha256'); ++------------------------------------------+ +| digest(Utf8("foo"), Utf8("sha256")) | ++------------------------------------------+ +| | ++------------------------------------------+ +``` + +##### `md5` + +Computes an MD5 128-bit checksum for a string expression. + +``` +md5(expression) +``` + +###### Arguments + +- **expression**: String expression to operate on. Can be a constant, column, or function, and any combination of operators. + +###### Example + +```sql +> select md5('foo'); ++-------------------------------------+ +| md5(Utf8("foo")) | ++-------------------------------------+ +| | ++-------------------------------------+ +``` + +##### `sha224` + +Computes the SHA-224 hash of a binary string. + +``` +sha224(expression) +``` + +###### Arguments + +- **expression**: String expression to operate on. Can be a constant, column, or function, and any combination of operators. + +###### Example + +```sql +> select sha224('foo'); ++------------------------------------------+ +| sha224(Utf8("foo")) | ++------------------------------------------+ +| | ++------------------------------------------+ +``` + +##### `sha256` + +Computes the SHA-256 hash of a binary string. + +``` +sha256(expression) +``` + +###### Arguments + +- **expression**: String expression to operate on. Can be a constant, column, or function, and any combination of operators. + +###### Example + +```sql +> select sha256('foo'); ++--------------------------------------+ +| sha256(Utf8("foo")) | ++--------------------------------------+ +| | ++--------------------------------------+ +``` + +##### `sha384` + +Computes the SHA-384 hash of a binary string. + +``` +sha384(expression) +``` + +###### Arguments + +- **expression**: String expression to operate on. Can be a constant, column, or function, and any combination of operators. + +###### Example + +```sql +> select sha384('foo'); ++-----------------------------------------+ +| sha384(Utf8("foo")) | ++-----------------------------------------+ +| | ++-----------------------------------------+ +``` + +##### `sha512` + +Computes the SHA-512 hash of a binary string. + +``` +sha512(expression) +``` + +###### Arguments + +- **expression**: String + +###### Example + +```sql +> select sha512('foo'); ++-------------------------------------------+ +| sha512(Utf8("foo")) | ++-------------------------------------------+ +| | ++-------------------------------------------+ +``` + +### Other Functions + +- [arrow_cast](#arrow-cast) +- [arrow_typeof](#arrow-typeof) +- [get_field](#get-field) +- [version](#version) + +##### `arrow_cast` + +Casts a value to a specific Arrow data type. + +``` +arrow_cast(expression, datatype) +``` + +###### Arguments + +- **expression**: Expression to cast. The expression can be a constant, column, or function, and any combination of operators. +- **datatype**: [Arrow data type](https://docs.rs/arrow/latest/arrow/datatypes/enum.DataType.html) name to cast to, as a string. The format is the same as that returned by [`arrow_typeof`] + +###### Example + +```sql +> select arrow_cast(-5, 'Int8') as a, + arrow_cast('foo', 'Dictionary(Int32, Utf8)') as b, + arrow_cast('bar', 'LargeUtf8') as c, + arrow_cast('2023-01-02T12:53:02', 'Timestamp(Microsecond, Some("+08:00"))') as d + ; ++----+-----+-----+---------------------------+ +| a | b | c | d | ++----+-----+-----+---------------------------+ +| -5 | foo | bar | 2023-01-02T12:53:02+08:00 | ++----+-----+-----+---------------------------+ +``` + +##### `arrow_typeof` + +Returns the name of the underlying [Arrow data type](https://docs.rs/arrow/latest/arrow/datatypes/enum.DataType.html) of the expression. + +``` +arrow_typeof(expression) +``` + +###### Arguments + +- **expression**: Expression to evaluate. The expression can be a constant, column, or function, and any combination of operators. + +###### Example + +```sql +> select arrow_typeof('foo'), arrow_typeof(1); ++---------------------------+------------------------+ +| arrow_typeof(Utf8("foo")) | arrow_typeof(Int64(1)) | ++---------------------------+------------------------+ +| Utf8 | Int64 | ++---------------------------+------------------------+ +``` + +##### `get_field` + +Returns a field within a map or a struct with the given key. +Note: most users invoke `get_field` indirectly via field access +syntax such as `my_struct_col['field_name']` which results in a call to +`get_field(my_struct_col, 'field_name')`. + +``` +get_field(expression1, expression2) +``` + +###### Arguments + +- **expression1**: The map or struct to retrieve a field for. +- **expression2**: The field name in the map or struct to retrieve data for. Must evaluate to a string. + +###### Example + +```sql +> create table t (idx varchar, v varchar) as values ('data','fusion'), ('apache', 'arrow'); +> select struct(idx, v) from t as c; ++-------------------------+ +| struct(c.idx,c.v) | ++-------------------------+ +| {c0: data, c1: fusion} | +| {c0: apache, c1: arrow} | ++-------------------------+ +> select get_field((select struct(idx, v) from t), 'c0'); ++-----------------------+ +| struct(t.idx,t.v)[c0] | ++-----------------------+ +| data | +| apache | ++-----------------------+ +> select get_field((select struct(idx, v) from t), 'c1'); ++-----------------------+ +| struct(t.idx,t.v)[c1] | ++-----------------------+ +| fusion | +| arrow | ++-----------------------+ +``` + +##### `version` + +Returns the version of DataFusion. + +``` +version() +``` + +###### Example + +```sql +> select version(); ++--------------------------------------------+ +| version() | ++--------------------------------------------+ +| Apache DataFusion 42.0.0, aarch64 on macos | ++--------------------------------------------+ +``` + + +## Aggregate Functions + +Aggregate functions operate on a set of values to compute a single result. + +Note: this documentation is in the process of being migrated to be [automatically created from the codebase]. +Please see the [Aggregate Functions (new)](#aggregate-functions-new) page for +the rest of the documentation. + +[automatically created from the codebase]: https://github.com/apache/datafusion/issues/12740 + +### Statistical + +- [covar](#covar) +- [regr_avgx](#regr-avgx) +- [regr_avgy](#regr-avgy) +- [regr_count](#regr-count) +- [regr_intercept](#regr-intercept) +- [regr_r2](#regr-r2) +- [regr_slope](#regr-slope) +- [regr_sxx](#regr-sxx) +- [regr_syy](#regr-syy) +- [regr_sxy](#regr-sxy) + +##### `covar` + +Returns the covariance of a set of number pairs. + +``` +covar(expression1, expression2) +``` + +###### Arguments + +- **expression1**: First expression to operate on. + Can be a constant, column, or function, and any combination of arithmetic operators. +- **expression2**: Second expression to operate on. + Can be a constant, column, or function, and any combination of arithmetic operators. + +##### `regr_slope` + +Returns the slope of the linear regression line for non-null pairs in aggregate columns. +Given input column Y and X: regr_slope(Y, X) returns the slope (k in Y = k\*X + b) using minimal RSS fitting. + +``` +regr_slope(expression1, expression2) +``` + +###### Arguments + +- **expression_y**: Expression to operate on. + Can be a constant, column, or function, and any combination of arithmetic operators. +- **expression_x**: Expression to operate on. + Can be a constant, column, or function, and any combination of arithmetic operators. + +##### `regr_avgx` + +Computes the average of the independent variable (input) `expression_x` for the non-null paired data points. + +``` +regr_avgx(expression_y, expression_x) +``` + +###### Arguments + +- **expression_y**: Dependent variable. + Can be a constant, column, or function, and any combination of arithmetic operators. +- **expression_x**: Independent variable. + Can be a constant, column, or function, and any combination of arithmetic operators. + +##### `regr_avgy` + +Computes the average of the dependent variable (output) `expression_y` for the non-null paired data points. + +``` +regr_avgy(expression_y, expression_x) +``` + +###### Arguments + +- **expression_y**: Dependent variable. + Can be a constant, column, or function, and any combination of arithmetic operators. +- **expression_x**: Independent variable. + Can be a constant, column, or function, and any combination of arithmetic operators. + +##### `regr_count` + +Counts the number of non-null paired data points. + +``` +regr_count(expression_y, expression_x) +``` + +###### Arguments + +- **expression_y**: Dependent variable. + Can be a constant, column, or function, and any combination of arithmetic operators. +- **expression_x**: Independent variable. + Can be a constant, column, or function, and any combination of arithmetic operators. + +##### `regr_intercept` + +Computes the y-intercept of the linear regression line. For the equation \(y = kx + b\), this function returns `b`. + +``` +regr_intercept(expression_y, expression_x) +``` + +###### Arguments + +- **expression_y**: Dependent variable. + Can be a constant, column, or function, and any combination of arithmetic operators. +- **expression_x**: Independent variable. + Can be a constant, column, or function, and any combination of arithmetic operators. + +##### `regr_r2` + +Computes the square of the correlation coefficient between the independent and dependent variables. + +``` +regr_r2(expression_y, expression_x) +``` + +###### Arguments + +- **expression_y**: Dependent variable. + Can be a constant, column, or function, and any combination of arithmetic operators. +- **expression_x**: Independent variable. + Can be a constant, column, or function, and any combination of arithmetic operators. + +##### `regr_sxx` + +Computes the sum of squares of the independent variable. + +``` +regr_sxx(expression_y, expression_x) +``` + +###### Arguments + +- **expression_y**: Dependent variable. + Can be a constant, column, or function, and any combination of arithmetic operators. +- **expression_x**: Independent variable. + Can be a constant, column, or function, and any combination of arithmetic operators. + +##### `regr_syy` + +Computes the sum of squares of the dependent variable. + +``` +regr_syy(expression_y, expression_x) +``` + +###### Arguments + +- **expression_y**: Dependent variable. + Can be a constant, column, or function, and any combination of arithmetic operators. +- **expression_x**: Independent variable. + Can be a constant, column, or function, and any combination of arithmetic operators. + +##### `regr_sxy` + +Computes the sum of products of paired data points. + +``` +regr_sxy(expression_y, expression_x) +``` + +###### Arguments + +- **expression_y**: Dependent variable. + Can be a constant, column, or function, and any combination of arithmetic operators. +- **expression_x**: Independent variable. + Can be a constant, column, or function, and any combination of arithmetic operators. + + +## Window Functions + +A _window function_ performs a calculation across a set of table rows that are somehow related to the current row. + +Note: this documentation is in the process of being migrated to be [automatically created from the codebase]. +Please see the [Window Functions (new)](#window-functions-new) page for +the rest of the documentation. + +[automatically created from the codebase]: https://github.com/apache/datafusion/issues/12740 + +Window functions are comparable to the type of calculation that can be done with an aggregate function. However, window functions do not cause rows to become grouped into a single output row like non-window aggregate calls would. Instead, the rows retain their separate identities. Behind the scenes, the window function is able to access more than just the current row of the query result + +Here is an example that shows how to compare each employee's salary with the average salary in his or her department: + +```sql +SELECT depname, empno, salary, avg(salary) OVER (PARTITION BY depname) FROM empsalary; + ++-----------+-------+--------+-------------------+ +| depname | empno | salary | avg | ++-----------+-------+--------+-------------------+ +| personnel | 2 | 3900 | 3700.0 | +| personnel | 5 | 3500 | 3700.0 | +| develop | 8 | 6000 | 5020.0 | +| develop | 10 | 5200 | 5020.0 | +| develop | 11 | 5200 | 5020.0 | +| develop | 9 | 4500 | 5020.0 | +| develop | 7 | 4200 | 5020.0 | +| sales | 1 | 5000 | 4866.666666666667 | +| sales | 4 | 4800 | 4866.666666666667 | +| sales | 3 | 4800 | 4866.666666666667 | ++-----------+-------+--------+-------------------+ +``` + +A window function call always contains an OVER clause directly following the window function's name and argument(s). This is what syntactically distinguishes it from a normal function or non-window aggregate. The OVER clause determines exactly how the rows of the query are split up for processing by the window function. The PARTITION BY clause within OVER divides the rows into groups, or partitions, that share the same values of the PARTITION BY expression(s). For each row, the window function is computed across the rows that fall into the same partition as the current row. The previous example showed how to count the average of a column per partition. + +You can also control the order in which rows are processed by window functions using ORDER BY within OVER. (The window ORDER BY does not even have to match the order in which the rows are output.) Here is an example: + +```sql +SELECT depname, empno, salary, + rank() OVER (PARTITION BY depname ORDER BY salary DESC) +FROM empsalary; + ++-----------+-------+--------+--------+ +| depname | empno | salary | rank | ++-----------+-------+--------+--------+ +| personnel | 2 | 3900 | 1 | +| develop | 8 | 6000 | 1 | +| develop | 10 | 5200 | 2 | +| develop | 11 | 5200 | 2 | +| develop | 9 | 4500 | 4 | +| develop | 7 | 4200 | 5 | +| sales | 1 | 5000 | 1 | +| sales | 4 | 4800 | 2 | +| personnel | 5 | 3500 | 2 | +| sales | 3 | 4800 | 2 | ++-----------+-------+--------+--------+ +``` + +There is another important concept associated with window functions: for each row, there is a set of rows within its partition called its window frame. Some window functions act only on the rows of the window frame, rather than of the whole partition. Here is an example of using window frames in queries: + +```sql +SELECT depname, empno, salary, + avg(salary) OVER(ORDER BY salary ASC ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING) AS avg, + min(salary) OVER(ORDER BY empno ASC ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS cum_min +FROM empsalary +ORDER BY empno ASC; + ++-----------+-------+--------+--------------------+---------+ +| depname | empno | salary | avg | cum_min | ++-----------+-------+--------+--------------------+---------+ +| sales | 1 | 5000 | 5000.0 | 5000 | +| personnel | 2 | 3900 | 3866.6666666666665 | 3900 | +| sales | 3 | 4800 | 4700.0 | 3900 | +| sales | 4 | 4800 | 4866.666666666667 | 3900 | +| personnel | 5 | 3500 | 3700.0 | 3500 | +| develop | 7 | 4200 | 4200.0 | 3500 | +| develop | 8 | 6000 | 5600.0 | 3500 | +| develop | 9 | 4500 | 4500.0 | 3500 | +| develop | 10 | 5200 | 5133.333333333333 | 3500 | +| develop | 11 | 5200 | 5466.666666666667 | 3500 | ++-----------+-------+--------+--------------------+---------+ +``` + +When a query involves multiple window functions, it is possible to write out each one with a separate OVER clause, but this is duplicative and error-prone if the same windowing behavior is wanted for several functions. Instead, each windowing behavior can be named in a WINDOW clause and then referenced in OVER. For example: + +```sql +SELECT sum(salary) OVER w, avg(salary) OVER w +FROM empsalary +WINDOW w AS (PARTITION BY depname ORDER BY salary DESC); +``` + +### Syntax + +The syntax for the OVER-clause is + +``` +function([expr]) + OVER( + [PARTITION BY expr[, …]] + [ORDER BY expr [ ASC | DESC ][, …]] + [ frame_clause ] + ) +``` + +where **frame_clause** is one of: + +``` + { RANGE | ROWS | GROUPS } frame_start + { RANGE | ROWS | GROUPS } BETWEEN frame_start AND frame_end +``` + +and **frame_start** and **frame_end** can be one of + +```sql +UNBOUNDED PRECEDING +offset PRECEDING +CURRENT ROW +offset FOLLOWING +UNBOUNDED FOLLOWING +``` + +where **offset** is an non-negative integer. + +RANGE and GROUPS modes require an ORDER BY clause (with RANGE the ORDER BY must specify exactly one column). + +### Aggregate functions + +All [aggregate functions](#aggregate-functions) can be used as window functions. + +### Ranking functions + +- [rank](#rank) +- [dense_rank](#dense-rank) +- [ntile](#ntile) + +##### `rank` + +Rank of the current row with gaps; same as row_number of its first peer. + +```sql +rank() +``` + +##### `dense_rank` + +Rank of the current row without gaps; this function counts peer groups. + +```sql +dense_rank() +``` + +##### `ntile` + +Integer ranging from 1 to the argument value, dividing the partition as equally as possible. + +```sql +ntile(expression) +``` + +###### Arguments + +- **expression**: An integer describing the number groups the partition should be split into + +### Analytical functions + +- [cume_dist](#cume-dist) +- [percent_rank](#percent-rank) +- [lag](#lag) +- [lead](#lead) +- [first_value](#first-value) +- [last_value](#last-value) +- [nth_value](#nth-value) + +##### `cume_dist` + +Relative rank of the current row: (number of rows preceding or peer with current row) / (total rows). + +```sql +cume_dist() +``` + +##### `percent_rank` + +Relative rank of the current row: (rank - 1) / (total rows - 1). + +```sql +percent_rank() +``` + +##### `lag` + +Returns value evaluated at the row that is offset rows before the current row within the partition; if there is no such row, instead return default (which must be of the same type as value). Both offset and default are evaluated with respect to the current row. If omitted, offset defaults to 1 and default to null. + +```sql +lag(expression, offset, default) +``` + +###### Arguments + +- **expression**: Expression to operate on +- **offset**: Integer. Specifies how many rows back the value of _expression_ should be retrieved. Defaults to 1. +- **default**: The default value if the offset is not within the partition. Must be of the same type as _expression_. + +##### `lead` + +Returns value evaluated at the row that is offset rows after the current row within the partition; if there is no such row, instead return default (which must be of the same type as value). Both offset and default are evaluated with respect to the current row. If omitted, offset defaults to 1 and default to null. + +```sql +lead(expression, offset, default) +``` + +###### Arguments + +- **expression**: Expression to operate on +- **offset**: Integer. Specifies how many rows forward the value of _expression_ should be retrieved. Defaults to 1. +- **default**: The default value if the offset is not within the partition. Must be of the same type as _expression_. + +##### `first_value` + +Returns value evaluated at the row that is the first row of the window frame. + +```sql +first_value(expression) +``` + +###### Arguments + +- **expression**: Expression to operate on + +##### `last_value` + +Returns value evaluated at the row that is the last row of the window frame. + +```sql +last_value(expression) +``` + +###### Arguments + +- **expression**: Expression to operate on + +##### `nth_value` + +Returns value evaluated at the row that is the nth row of the window frame (counting from 1); null if no such row. + +```sql +nth_value(expression, n) +``` + +###### Arguments + +- **expression**: The name the column of which nth value to retrieve +- **n**: Integer. Specifies the _n_ in nth diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/functions/geo.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/functions/geo.md new file mode 100644 index 000000000..f76194996 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/functions/geo.md @@ -0,0 +1,444 @@ +--- +keywords: [地理函数, 空间关系, SQL 查询, 数据库地理, 地理空间] +description: 列出了 GreptimeDB 中的所有地理空间相关函数,包括函数的定义、使用方法和相关的 SQL 查询示例。 +--- + +import TOCInline from '@theme/TOCInline'; + +# 地理函数 + +这个页面列出了 GreptimeDB 中的所有地理空间相关函数。当您启用了 +`common-function/geo` 特性(默认为开启状态)时,这些函数才会生效。 + + + +## Geo 数据类型函数 + +地理相关数据类型转换。 + +### `wkt_point_from_latlng` + +将纬度、经度转换成 WKT 点。 + +```sql +SELECT wkt_point_from_latlng(37.76938, -122.3889) AS point; +``` + +## Geohash + +了解 [更多关于 geohash 编码](https://en.wikipedia.org/wiki/Geohash)。 + +### `geohash` + +从纬度、经度和分辨率获取 geohash 编码的字符串。 + +```sql +SELECT geohash(37.76938, -122.3889, 11); +``` + +### `geohash_neighbours` + +给定坐标和分辨率获取所有 geohash 邻接点。 + +请注意,此函数返回一个字符串数组,并且仅在我们的HTTP查询API和Postgres通道上生效。 + +```sql +SELECT geohash_neighbours(37.76938, -122.3889, 11); +``` + +## H3 + +H3 地理坐标编码算法。[了解更多](https://h3geo.org/)。 + +### `h3_latlng_to_cell` + +将坐标(纬度,经度)编码为指定分辨率下的 h3 索引,并返回该单元格的 UInt64 表示。 + +```sql +SELECT h3_latlng_to_cell(37.76938, -122.3889, 1); +``` + +### `h3_latlng_to_cell_string` + +类似于 `h3_latlng_to_cell` ,但返回字符串编码格式。 + +```sql +h3_latlng_to_cell_string(37.76938, -122.3889, 1); +``` + +### `h3_cell_to_string` + +将单元格索引(UInt64)转换为其字符串表示形式。 + +```sql +SELECT h3_cell_to_string(h3_latlng_to_cell(37.76938, -122.3889, 8)); +``` + +### `h3_string_to_cell` + +将十六进制编码的单元 ID 转换为其 UInt64 形式。 + +```sql +h3_string_to_cell(h3_latlng_to_cell_string(37.76938, -122.3889, 8::UInt64)); +``` + +### `h3_cell_center_latlng` + +返回单元中心的纬度和经度。 + +请注意,此函数返回一个浮点数数组,并且仅在我们的 HTTP 查询 API 和 Postgres 通道上有效。 + +```sql +SELECT h3_cell_center_latlng(h3_latlng_to_cell(37.76938, -122.3889, 8)); +``` + +### `h3_cell_resolution` + +给定单元格的返回分辨率。 + +```sql +SELECT h3_cell_resolution(h3_latlng_to_cell(37.76938, -122.3889, 8)); +``` + +### `h3_cell_base` + +返回给定单元的 Base 单元。 + +```sql +SELECT h3_cell_base(h3_latlng_to_cell(37.76938, -122.3889, 8)); +``` + +### `h3_cell_is_pentagon` + +如果单元格是五边形,则返回 true。 + +```sql +SELECT h3_cell_is_pentagon(h3_latlng_to_cell(37.76938, -122.3889, 8)); +``` + +### `h3_cell_parent` + +返回给定分辨率下单元的父单元。 + +```sql +h3_cell_parent(h3_latlng_to_cell(37.76938, -122.3889, 8), 6); +``` + +### `h3_cell_to_children` + +根据给定的分辨率返回子单元格。 + +请注意,此函数返回一个 UInt64 数组,并且仅在我们的 HTTP 查询 API 和 Postgres 通道上生效。 + +```sql +h3_cell_to_children(h3_latlng_to_cell(37.76938, -122.3889, 8), 10); +``` + +### `h3_cell_to_children_size` + +根据给定的分辨率,返回单元格中的子单元数量。 + + +```sql +h3_cell_to_children_size(h3_latlng_to_cell(37.76938, -122.3889, 8), 10); +``` + +### `h3_cell_to_child_pos` + +根据给定分辨率,返回单元在其父单元的位置。位置是单元在所有子单元中的索引。 + +```sql +h3_cell_to_child_pos(h3_latlng_to_cell(37.76938, -122.3889, 8), 6) +``` + +### `h3_child_pos_to_cell` + +在给定分辨率下,返回父单元中给定位置的单元。 + +参数: + +- 位置 +- 单元索引 +- 分辨率 + +```sql +h3_child_pos_to_cell(25, h3_latlng_to_cell(37.76938, -122.3889, 8), 11); +``` + +### `h3_cells_contains` + +测试输入的单元集合是否包含指定的单元,或其父单元。 + +参数: + +- 单元集合: 可以是 int64/uint64/string 数组, 或逗号分割的字符串单元 ID +- 单元索引 + +```sql +SELECT + h3_cells_contains('86283470fffffff,862834777ffffff, 862834757ffffff, 86283471fffffff, 862834707ffffff', '8b283470d112fff') AS R00, + h3_cells_contains(['86283470fffffff', '862834777ffffff', '862834757ffffff', '86283471fffffff', '862834707ffffff'], '8b283470d112fff') AS R11, + h3_cells_contains([604189641255419903, 604189643000250367, 604189642463379455, 604189641523855359, 604189641121202175], 604189641792290815) AS R21; +``` + +### `h3_grid_disk` + +返回给定单元格的 k 个距离对应的单元格。 + +请注意,此函数返回一个 UInt64 数组,并且仅能在我们的 HTTP 查询 API 和 Postgres 通道上工作。 + +```sql +h3_grid_disk(h3_latlng_to_cell(37.76938, -122.3889, 8), 3); +``` + +### `h3_grid_disk_distances` + +返回给定单元格范围内所有距离为 *k* 的单元格。 + +请注意,此函数返回一个 UInt64 数组,并且仅适用于我们的 HTTP 查询 API 和 Postgres 通道。 + +```sql +h3_grid_disk_distance(h3_latlng_to_cell(37.76938, -122.3889, 8), 3); +``` + +### `h3_grid_distance` + +返回两单元的距离。 + +```sql +SELECT + h3_grid_distance(cell1, cell2) AS distance, +FROM + ( + SELECT + h3_latlng_to_cell(37.76938, -122.3889, 8) AS cell1, + h3_latlng_to_cell(39.634, -104.999, 8) AS cell2 + ); +``` + +### `h3_grid_path_cells` + +此函数可在两个单元格之间返回路径单元格。请注意,如果两个单元格相距很远,该函数可能会失败。 + +```sql +SELECT + h3_grid_path_cells(cell1, cell2) AS path_cells, +FROM + ( + SELECT + h3_latlng_to_cell(37.76938, -122.3889, 8) AS cell1, + h3_latlng_to_cell(39.634, -104.999, 8) AS cell2 + ); +``` + +### `h3_distance_sphere_km` + +返回两个单元中心的大圆距离,单位:千米 + +```sql +SELECT + round(h3_distance_sphere_km(cell1, cell2), 5) AS sphere_distance +FROM + ( + SELECT + h3_string_to_cell('86283082fffffff') AS cell1, + h3_string_to_cell('86283470fffffff') AS cell2 + ); + +``` + +### `h3_distance_degree` + +返回两个单元中心的欧式距离,单位:度 + +```sql +SELECT + round(h3_distance_degree(cell1, cell2), 14) AS euclidean_distance +FROM + ( + SELECT + h3_string_to_cell('86283082fffffff') AS cell1, + h3_string_to_cell('86283470fffffff') AS cell2 + ); +``` + +## S2 + +了解[更多关于 S2 编码的信息](http://s2geometry.io/). + +### `s2_latlng_to_cell` + +给定坐标对应的 s2 单元索引。 + +```sql +SELECT s2_latlng_to_cell(37.76938, -122.3889); +``` + +### `s2_cell_to_token` + +给定单元格的字符串表示形式。 + +```sql +SELECT s2_cell_to_token(s2_latlng_to_cell(37.76938, -122.3889)); +``` + +### `s2_cell_level` + +返回给定单元格的级别。 + +```sql +SELECT s2_cell_level(s2_latlng_to_cell(37.76938, -122.3889)); +``` + +### `s2_cell_parent` + +返回给定单元格位于特定级别的父单元。 + +```sql +SELECT s2_cell_parent(s2_latlng_to_cell(37.76938, -122.3889), 3); +``` + +## 编码 + +### `json_encode_path` + +将纬度、经度按时间戳排序并编码为一个 JSON 数组。 + +参数: + +- 纬度 +- 经度 +- 时间戳 + +返回一个字符串类型的JSON数组。请注意,结果坐标中的顺序为 [经度, 纬度],以符合 GeoJSON 规范。 + +```sql +SELECT json_encode_path(lat, lon, ts); +``` + +示例输出: + +```json +[[-122.3888,37.77001],[-122.3839,37.76928],[-122.3889,37.76938],[-122.382,37.7693]] +``` + +## 空间关系 + +### `st_contains` + +测试两个空间对象是否为包含关系。 + +参数:WKT 编码的地理对象。 + +```sql +SELECT + st_contains(polygon1, p1), + st_contains(polygon2, p1), +FROM + ( + SELECT + wkt_point_from_latlng(37.383287, -122.01325) AS p1, + 'POLYGON ((-122.031661 37.428252, -122.139829 37.387072, -122.135365 37.361971, -122.057759 37.332222, -121.987707 37.328946, -121.943754 37.333041, -121.919373 37.349145, -121.945814 37.376705, -121.975689 37.417345, -121.998696 37.409164, -122.031661 37.428252))' AS polygon1, + 'POLYGON ((-121.491698 38.653343, -121.582353 38.556757, -121.469721 38.449287, -121.315883 38.541721, -121.491698 38.653343))' AS polygon2, + ); + +``` + +### `st_within` + +测试两个空间对象是否为被包含关系。 + +参数:WKT 编码的地理对象。 + +```sql +SELECT + st_within(p1, polygon1), + st_within(p1, polygon2), + ROM + ( + SELECT + wkt_point_from_latlng(37.383287, -122.01325) AS p1, + 'POLYGON ((-122.031661 37.428252, -122.139829 37.387072, -122.135365 37.361971, -122.057759 37.332222, -121.987707 37.328946, -121.943754 37.333041, -121.919373 37.349145, -121.945814 37.376705, -121.975689 37.417345, -121.998696 37.409164, -122.031661 37.428252))' AS polygon1, + 'POLYGON ((-121.491698 38.653343, -121.582353 38.556757, -121.469721 38.449287, -121.315883 38.541721, -121.491698 38.653343))' AS polygon2, + ); + +``` + + +### `st_intersects` + +测试两个空间对象是否为重叠关系。 + +参数:WKT 编码的地理对象。 + +```sql +SELECT + st_intersects(polygon1, polygon2), + st_intersects(polygon1, polygon3), +FROM + ( + SELECT + 'POLYGON ((-122.031661 37.428252, -122.139829 37.387072, -122.135365 37.361971, -122.057759 37.332222, -121.987707 37.328946, -121.943754 37.333041, -121.919373 37.349145, -121.945814 37.376705, -121.975689 37.417345, -121.998696 37.409164, -122.031661 37.428252))' AS polygon1, + 'POLYGON ((-121.491698 38.653343, -121.582353 38.556757, -121.469721 38.449287, -121.315883 38.541721, -121.491698 38.653343))' AS polygon2, + 'POLYGON ((-122.089628 37.450332, -122.20535 37.378342, -122.093062 37.36088, -122.044301 37.372886, -122.089628 37.450332))' AS polygon3, + ); + +``` + + +## Spatial Measurement + +### `st_distance` + +返回两个对象的在 WGS84 坐标系下的欧式距离,单位:度。 + +参数:WKT 编码的地理对象。 + +```sql +SELECT + st_distance(p1, p2) AS euclidean_dist, + st_distance(p1, polygon1) AS euclidean_dist_pp, +FROM + ( + SELECT + wkt_point_from_latlng(37.76938, -122.3889) AS p1, + wkt_point_from_latlng(38.5216, -121.4247) AS p2, + 'POLYGON ((-121.491698 38.653343, -121.582353 38.556757, -121.469721 38.449287, -121.315883 38.541721, -121.491698 38.653343))' AS polygon1, + ); +``` + +### `st_distance_sphere_m` + +返回两点的大圆距离,单位:米。 + +参数:WKT 编码的地理对象。 + +```sql +SELECT + st_distance_sphere_m(p1, p2) AS sphere_dist_m, +FROM + ( + SELECT + wkt_point_from_latlng(37.76938, -122.3889) AS p1, + wkt_point_from_latlng(38.5216, -121.4247) AS p2, + ); + +``` + +### `st_area` + +返回地理对象的面积。 + +参数:WKT 编码的地理对象。 + +```sql +SELECT + st_area(p1) as area_point, + st_area(polygon1) as area_polygon, +FROM + ( + SELECT + wkt_point_from_latlng(37.76938, -122.3889) AS p1, + 'POLYGON ((-121.491698 38.653343, -121.582353 38.556757, -121.469721 38.449287, -121.315883 38.541721, -121.491698 38.653343))' AS polygon1, + ); +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/functions/json.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/functions/json.md new file mode 100644 index 000000000..5166773b1 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/functions/json.md @@ -0,0 +1,125 @@ +--- +keywords: [JSON函数, 数据转换, SQL 查询, 数据库 JSON, JSON 操作] +description: 列出了 GreptimeDB 中的所有 JSON 函数,包括函数的定义、使用方法和相关的 SQL 查询示例。 +--- + +# JSON 函数 + +本页面列出了 GreptimeDB 中所有 JSON 类型相关的函数。 + + +## 转换 + +JSON 类型与其他类型的值之间的转换。 + +* `parse_json(string)` 尝试将字符串解析为 JSON 类型。非法的 JSON 字符串将返回错误。 +* `json_to_string(json)` 将 JSON 类型的值转换为字符串。 + +```sql +SELECT json_to_string(parse_json('{"a": 1, "b": 2}')); + ++----------------------------------------------------------+ +| json_to_string(parse_json(Utf8("{\"a\": 1, \"b\": 2}"))) | ++----------------------------------------------------------+ +| {"a":1,"b":2} | ++----------------------------------------------------------+ +``` + +## 提取 + +通过给定的路径和给定的数据类型,从 JSON 中提取值。 + +* `json_get_bool(json, path)` 按照路径 `path` 从 JSON 中获取布尔值。 +* `json_get_int(json, path)` 按照路径 `path` 从 JSON 中获取整数值。布尔值将被转换为整数。 +* `json_get_float(json, path)` 按照路径 `path` 从 JSON 中获取浮点数值。布尔值、整数值将被转换为浮点数。 +* `json_get_string(json, path)` 按照路径 `path` 从 JSON 中获取字符串。所有类型的 JSON 值都将被转换为字符串,包括数组、对象和 null。 + +`path` 是一个用于从 JSON 值中选择和提取元素的字符串。`path` 中支持的操作符有: + +| 操作符 | 描述 | 示例 | +|--------------------------|--------------------------------------------------------------|--------------------| +| `$` | 根元素 | `$` | +| `@` | 过滤表达式中的当前元素 | `$.event?(@ == 1)` | +| `.*` | 选择对象中的所有元素 | `$.*` | +| `.` | 选择对象中匹配名称的元素 | `$.event` | +| `:` | `.` 的别名 | `$:event` | +| `[""]` | `.` 的别名 | `$["event"]` | +| `[*]` | 选择数组中的所有元素 | `$[*]` | +| `[, ..]` | 选择数组中基于0的第 `n` 个元素 | `$[1, 2]` | +| `[last - , ..]` | 选择数组中最后一个元素之前的第 `n` 个元素 | `$[0, last - 1]` | +| `[ to , ..]` | 选择数组中某个范围内的所有元素 | `$[1 to last - 2]` | +| `?()` | 选择所有匹配过滤表达式的元素 | `$?(@.price < 10)` | + +如果 `path` 是无效的,函数将返回 `NULL`。 + +```sql +SELECT json_get_int(parse_json('{"a": {"c": 3}, "b": 2}'), 'a.c'); + ++-----------------------------------------------------------------------+ +| json_get_int(parse_json(Utf8("{"a": {"c": 3}, "b": 2}")),Utf8("a.c")) | ++-----------------------------------------------------------------------+ +| 3 | ++-----------------------------------------------------------------------+ +``` + +## 验证 + +检查 JSON 值的类型。 + +* `json_is_null(json)` 检查 JSON 中的值是否为 `NULL`。 +* `json_is_bool(json)` 检查 JSON 中的值是否为布尔值。 +* `json_is_int(json)` 检查 JSON 中的值是否为整数。 +* `json_is_float(json)` 检查 JSON 中的值是否为浮点数。 +* `json_is_string(json)` 检查 JSON 中的值是否为字符串。 +* `json_is_array(json)` 检查 JSON 中的值是否为数组。 +* `json_is_object(json)` 检查 JSON 中的值是否为对象。 + +```sql +SELECT json_is_array(parse_json('[1, 2, 3]')); + ++----------------------------------------------+ +| json_is_array(parse_json(Utf8("[1, 2, 3]"))) | ++----------------------------------------------+ +| 1 | ++----------------------------------------------+ + +SELECT json_is_object(parse_json('1')); + ++---------------------------------------+ +| json_is_object(parse_json(Utf8("1"))) | ++---------------------------------------+ +| 0 | ++---------------------------------------+ +``` + +* `json_path_exists(json, path)` 检查 JSON 中是否存在指定的路径。 + +如果 `path` 是无效的,函数将返回错误。 + +如果 `path` 或 `json` 是 `NULL`,函数将返回 `NULL`。 + +```sql +SELECT json_path_exists(parse_json('{"a": 1, "b": 2}'), 'a'); + ++------------------------------------------------------------------+ +| json_path_exists(parse_json(Utf8("{"a": 1, "b": 2}")),Utf8("a")) | ++------------------------------------------------------------------+ +| 1 | ++------------------------------------------------------------------+ + +SELECT json_path_exists(parse_json('{"a": 1, "b": 2}'), 'c.d'); + ++--------------------------------------------------------------------+ +| json_path_exists(parse_json(Utf8("{"a": 1, "b": 2}")),Utf8("c.d")) | ++--------------------------------------------------------------------+ +| 0 | ++--------------------------------------------------------------------+ + +SELECT json_path_exists(parse_json('{"a": 1, "b": 2}'), NULL); + ++-------------------------------------------------------------+ +| json_path_exists(parse_json(Utf8("{"a": 1, "b": 2}")),NULL) | ++-------------------------------------------------------------+ +| NULL | ++-------------------------------------------------------------+ +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/functions/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/functions/overview.md new file mode 100644 index 000000000..c7f589142 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/functions/overview.md @@ -0,0 +1,237 @@ +--- +keywords: [函数概述, Datafusion 函数, GreptimeDB 函数, SQL 查询, 数据库函数] +description: 提供了 GreptimeDB 中函数的概述,包括函数的分类、定义和使用方法。 +--- + +import TOCInline from '@theme/TOCInline'; + +# 概述 + + + + + +## Datafusion 函数 + +由于 GreptimeDB 的查询引擎是基于 Apache Arrow DataFusion 构建的,GreptimeDB 继承了 DataFusion 中所有内置的函数。这些函数包括: + +* **聚合函数**: 如 `COUNT`、`SUM`、`MIN`、`MAX` 等。详细列表请参阅 [聚合函数](./df-functions.md#aggregate-functions) +* **标量函数**: 如 `ABS`、`COS`、`FLOOR` 等。详细列表请参阅 [标量函数](./df-functions.md#scalar-functions) +* **窗口函数**: 对相关的一组行记录执行计算。详细列表请参阅 [窗口函数](./df-functions.md#window-functions) + +要查看所有 DataFusion 函数,请参阅 [DataFusion 函数](./df-functions)。 + +### `arrow_cast` + +`arrow_cast` 函数来自 DataFusion 的 [`arrow_cast`](./df-functions.md#arrow-cast)。其用法如下: + +```sql +arrow_cast(expression, datatype) +``` + +其中 `datatype` 可以是此 [列表](https://arrow.apache.org/datafusion/user-guide/sql/data_types.html) 中的任何有效 Arrow 数据类型。四种时间戳类型是: + +- Timestamp(Second, None) +- Timestamp(Millisecond, None) +- Timestamp(Microsecond, None) +- Timestamp(Nanosecond, None) + +(注意 `None` 表示时间戳不考虑时区) + +## GreptimeDB 函数 + +### 字符串函数 + +DataFusion [字符串函数](./df-functions.md#string-functions)。GreptimeDB 提供: +* `matches(expression, pattern)` 用于全文检索。 + +阅读[查询日志](/user-guide/logs/query-logs.md)文档获取更多详情。 + +### 数学函数 + +DataFusion [数学函数](./df-functions.md#math-functions)。GreptimeDB 额外提供: +* `clamp(value, lower, upper)` 将给定值限制在上下界之间: +```sql +SELECT CLAMP(10, 0, 1); + ++------------------------------------+ +| clamp(Int64(10),Int64(0),Int64(1)) | ++------------------------------------+ +| 1 | ++------------------------------------+ +``` + +```sql +SELECT CLAMP(0.5, 0, 1); + ++---------------------------------------+ +| clamp(Float64(0.5),Int64(0),Int64(1)) | ++---------------------------------------+ +| 0.5 | ++---------------------------------------+ +``` + +* `mod(x, y)` 获取一个数除以另一个数的余数: +```sql +SELECT mod(18, 4); + ++-------------------------+ +| mod(Int64(18),Int64(4)) | ++-------------------------+ +| 2 | ++-------------------------+ +``` + +* `pow(x, y)` 获取一个数的幂值: +```sql +SELECT pow(2, 10); + ++-------------------------+ +| pow(Int64(2),Int64(10)) | ++-------------------------+ +| 1024 | ++-------------------------+ +``` + +### 日期和时间函数 + +DataFusion [时间和日期函数](./df-functions.md#time-and-date-functions)。GreptimeDB 额外提供: + +* `date_add(expression, interval)` 向 Timestamp、Date 或 DateTime 添加一个间隔值: + +```sql +SELECT date_add('2023-12-06'::DATE, '3 month 5 day'); +``` + +``` ++----------------------------------------------------+ +| date_add(Utf8("2023-12-06"),Utf8("3 month 5 day")) | ++----------------------------------------------------+ +| 2024-03-11 | ++----------------------------------------------------+ +``` + +* `date_sub(expression, interval)` 从 Timestamp、Date 或 DateTime 减去一个间隔值: + +```sql +SELECT date_sub('2023-12-06 07:39:46.222'::TIMESTAMP_MS, INTERVAL '5 day'); +``` + +``` ++-----------------------------------------------------------------------------------------------------------------------------------------+ +| date_sub(arrow_cast(Utf8("2023-12-06 07:39:46.222"),Utf8("Timestamp(Millisecond, None)")),IntervalMonthDayNano("92233720368547758080")) | ++-----------------------------------------------------------------------------------------------------------------------------------------+ +| 2023-12-01 07:39:46.222000 | ++-----------------------------------------------------------------------------------------------------------------------------------------+ +``` + +* `date_format(expression, fmt)` 将 Timestamp、Date 或 DateTime格式化: + +```sql +SELECT date_format('2023-12-06 07:39:46.222'::TIMESTAMP, '%Y-%m-%d %H:%M:%S:%3f'); +``` + +``` ++-----------------------------------------------------------------------------------------------------------------------------+ +| date_format(arrow_cast(Utf8("2023-12-06 07:39:46.222"),Utf8("Timestamp(Millisecond, None)")),Utf8("%Y-%m-%d %H:%M:%S:%3f")) | ++-----------------------------------------------------------------------------------------------------------------------------+ +| 2023-12-06 07:39:46:222 | ++-----------------------------------------------------------------------------------------------------------------------------+ +``` + +支持的格式化符号请参阅 [chrono::format::strftime](https://docs.rs/chrono/latest/chrono/format/strftime/index.html) 模块。 + +* `to_unixtime(expression)` 将表达式转换为 Unix 时间戳(秒)。参数可以是整数(毫秒 Unix 时间戳)、Timestamp、Date、DateTime 或字符串类型。如果参数是字符串类型,函数将首先尝试将其转换为 DateTime、Timestamp 或 Date。 + +```sql +select to_unixtime('2023-03-01T06:35:02Z'); +``` + +``` ++-------------------------------------------+ +| to_unixtime(Utf8("2023-03-01T06:35:02Z")) | ++-------------------------------------------+ +| 1677652502 | ++-------------------------------------------+ +``` + +```sql +select to_unixtime('2023-03-01'::date); +``` + +``` ++---------------------------------+ +| to_unixtime(Utf8("2023-03-01")) | ++---------------------------------+ +| 1677628800 | ++---------------------------------+ +``` + +* `timezone()` 查询当前会话时区: + +```sql +select timezone(); +``` + +``` ++------------+ +| timezone() | ++------------+ +| UTC | ++------------+ +``` + +### 系统函数 + +* `isnull(expression)` 检查表达式是否为 `NULL`: +```sql + SELECT isnull(1); + + +------------------+ +| isnull(Int64(1)) | ++------------------+ +| 0 | ++------------------+ +``` + +```sql +SELECT isnull(NULL); + ++--------------+ +| isnull(NULL) | ++--------------+ +| 1 | ++--------------+ +``` + +* `build()` 查询 GreptimeDB 构建信息。 +* `version()` 查询 GreptimeDB 版本信息。 +* `database()` 查询当前会话数据库: + +```sql +select database(); + ++------------+ +| database() | ++------------+ +| public | ++------------+ +``` + +### 管理函数 + +GreptimeDB 提供了 `ADMIN` 语句来执行管理函数,请阅读 [ADMIN](/reference/sql/admin.md) 文档。 + +### JSON 函数 + +[了解 GreptimeDB 中 JSON 相关的函数](./json.md)。 + +### 地理函数 + +[了解 GreptimeDB 中轨迹、地理编码相关的地理函数](./geo.md)。 + +### 向量函数 + +[了解 GreptimeDB 中向量相关的函数](./vector.md)。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/functions/vector.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/functions/vector.md new file mode 100644 index 000000000..8169db14f --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/functions/vector.md @@ -0,0 +1,107 @@ +--- +keywords: [向量函数, 距离计算, 向量运算, SQL 查询, 数据库向量] +description: 列出了 GreptimeDB 中的所有向量函数,包括函数的定义、使用方法和相关的 SQL 查询示例。 +--- + +# 向量函数 + +本页面列出了 GreptimeDB 中所有支持的向量相关函数。向量函数主要用于处理向量运算,比如距离计算、相似度度量等。 + +## 距离计算 + +GreptimeDB 提供了以下常用的距离计算函数: + +* `vec_l2sq_distance(vec1, vec2)`:计算两个向量之间的 L2 距离的平方。 +* `vec_cos_distance(vec1, vec2)`:计算两个向量之间的余弦距离。 +* `vec_dot_product(vec1, vec2)`:计算两个向量之间的点积。 + +这些函数接受向量值作为参数。你可以通过 `parse_vec` 函数将字符串转变为向量值,例如 `parse_vec('[1.0, 2.0, 3.0]')`。同时,字符串格式的向量(例如 `[1.0, 2.0, 3.0]`)也可以直接使用,它们会被自动转换。无论采用哪种方式,向量的维度必须保持一致。 + +### `vec_l2sq_distance` + +计算两个向量之间的平方欧几里得距离(L2 距离的平方)。L2 距离是几何空间中两个点之间的直线距离,此函数返回其平方值以提高计算效率。 + +示例: + +```sql +SELECT vec_l2sq_distance(parse_vec('[1.0, 2.0, 3.0]'), parse_vec('[2.0, 1.0, 4.0]')); +``` + +或者 + +```sql +SELECT vec_l2sq_distance('[1.0, 2.0, 3.0]', '[2.0, 1.0, 4.0]'); +``` + +说明: +* 参数为两个维度一致的向量。 +* 返回值类型为 `Float32` 标量。 + +### `vec_cos_distance` + +计算两个向量之间的余弦距离。余弦距离是两个向量之间的夹角余弦值,用于衡量向量之间的相似度。 + +示例: + +```sql +SELECT vec_cos_distance(parse_vec('[1.0, 2.0, 3.0]'), parse_vec('[2.0, 1.0, 4.0]')); +``` + +或者 + +```sql +SELECT vec_cos_distance('[1.0, 2.0, 3.0]', '[2.0, 1.0, 4.0]'); +``` + +说明: +* 参数为两个维度一致的向量。 +* 返回值类型为 `Float32` 标量。 + +### `vec_dot_product` + +计算两个向量之间的点积。点积是两个向量对应元素的乘积之和,常用于度量两个向量的相似性或用于机器学习的线性变换中。 + +示例: + +```sql +SELECT vec_dot_product(parse_vec('[1.0, 2.0, 3.0]'), parse_vec('[2.0, 1.0, 4.0]')); +``` + +或者 + +```sql +SELECT vec_dot_product('[1.0, 2.0, 3.0]', '[2.0, 1.0, 4.0]'); +``` + +说明: +* 参数为两个维度一致的向量。 +* 返回值类型为 `Float32` 标量。 + +## 转换函数 + +在处理数据库中的向量数据时,GreptimeDB 提供了方便的函数,用于在字符串和向量值之间进行转换。 + +### `parse_vec` + +将字符串转换为向量值。字符串必须以方括号 `[]` 包围,并且包含 `Float32` 类型的元素,元素之间用逗号分隔。 + +示例: + +```sql +CREATE TABLE vectors ( + ts TIMESTAMP, + vec_col VECTOR(3) +); + +INSERT INTO vectors (ts, vec_col) VALUES ('2024-11-18 00:00:01', parse_vec('[1.0, 2.0, 3.0]')); +``` + +### `vec_to_string` + +将向量值转换为字符串。转换后的字符串格式为 `[, , ...]`。 + +示例: + +```sql +SELECT vec_to_string(vec_col) FROM vectors; +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/group_by.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/group_by.md similarity index 87% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/group_by.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/group_by.md index f1dcc082d..c7b5cfc0f 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/group_by.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/group_by.md @@ -1,3 +1,8 @@ +--- +keywords: [SQL GROUP BY 子句, 数据分组, 聚合函数, 数据汇总, SQL 示例] +description: GROUP BY 语句用于对具有相同值的行进行分组,通常与聚合函数一起使用。 +--- + # GROUP BY SQL 中的 `GROUP BY` 语句用于对具有一个或多个列中的相同值的行进行分组。 @@ -65,4 +70,4 @@ FROM system_metrics GROUP BY dt ``` -请参考 [date_trunc](./functions.md#date_trunc) 获取更多信息。 +请参考 [date_trunc](./functions/overview.md#date_trunc) 获取更多信息。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/information-schema/build-info.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/information-schema/build-info.md similarity index 61% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/information-schema/build-info.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/information-schema/build-info.md index e9f296a28..e889ab537 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/information-schema/build-info.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/information-schema/build-info.md @@ -1,3 +1,8 @@ +--- +keywords: [BUILD_INFO 表, 构建信息, 版本信息, SQL查询, 数据库构建] +description: 提供了 GreptimeDB 构建信息的相关内容,包括版本信息、构建时间和相关的 SQL 查询示例。 +--- + # BUILD_INFO `BUILD_INFO` 表提供了系统的构建信息: @@ -12,9 +17,9 @@ SELECT * FROM BUILD_INFO; ```sql +------------+------------------------------------------+------------------+-----------+-------------+ -| git_branch | git_commit | git_commit_short | git_dirty | pkg_version | +| git_branch | git_commit | git_commit_short | git_clean | pkg_version | +------------+------------------------------------------+------------------+-----------+-------------+ -| main | 92a8e863ded618fe1be93f799360015b4f8f28b6 | 92a8e86 | true | 0.7.1 | +| | c595a56ac89bef78b19a76aa60d8c6bcac7354a5 | c595a56a | true | 0.9.0 | +------------+------------------------------------------+------------------+-----------+-------------+ ``` @@ -23,5 +28,5 @@ SELECT * FROM BUILD_INFO; * `branch`:构建的 git 分支名称。 * `git_commit`:提交构建的 `commit`。 * `git_commit_short`:提交构建的 `commit` 缩写。 -* `git_dirty`:如果构建源目录包含未提交的更改,则为 `true`。 +* `git_clean`:如果构建源目录包含了所有提交的更改,则为 `true`。 * `pkg_version`:GreptimeDB 版本。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/information-schema/character-sets.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/information-schema/character-sets.md similarity index 77% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/information-schema/character-sets.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/information-schema/character-sets.md index 6dbcbf02b..779d06d61 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/information-schema/character-sets.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/information-schema/character-sets.md @@ -1,3 +1,8 @@ +--- +keywords: [CHARACTER_SETS 表, 字符集, SQL 查询, 数据库字符集, 字符集信息] +description: 介绍了 GreptimeDB 中的字符集,包括字符集的定义、使用方法和相关的 SQL 查询示例。 +--- + # CHARACTER_SETS `CHARACTER_SETS` 提供了 GreptimeDB 支持的可用字符集。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/information-schema/cluster-info.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/information-schema/cluster-info.md new file mode 100644 index 000000000..f6527fd93 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/information-schema/cluster-info.md @@ -0,0 +1,77 @@ +--- +keywords: [CLUSTER_INFO 表, 集群信息, 节点信息, SQL查询, 数据库集群] +description: 提供了 GreptimeDB 集群信息的相关内容,包括集群状态、节点信息和相关的 SQL 查询示例。 +--- + +# CLUSTER_INFO + +`CLUSTER_INFO` 表提供了集群的节点拓扑信息。 + + +```sql +USE INFORMATION_SCHEMA; + +DESC TABLE CLUSTER_INFO; +``` + +输出如下: + +```sql ++-------------+----------------------+------+------+---------+---------------+ +| Column | Type | Key | Null | Default | Semantic Type | ++-------------+----------------------+------+------+---------+---------------+ +| peer_id | Int64 | | NO | | FIELD | +| peer_type | String | | NO | | FIELD | +| peer_addr | String | | YES | | FIELD | +| version | String | | NO | | FIELD | +| git_commit | String | | NO | | FIELD | +| start_time | TimestampMillisecond | | YES | | FIELD | +| uptime | String | | YES | | FIELD | +| active_time | String | | YES | | FIELD | ++-------------+----------------------+------+------+---------+---------------+ +``` + + +每个列的含义: + +* `peer_id`: 节点的服务器 ID。对于 standalone 来讲,该字段总是为 `0`,对于集群模式下的 frontend 该字段总为 `-1`。因为在这两种情况下,该字段没有实际含义。 +* `peer_type`: 节点类型, 分布式集群里可能是 `METASRV`、`FRONTEND` 或者 `DATANODE`。单机模式显示为 `STANDALONE`。 +* `peer_addr`: 节点的 gRPC 服务地址。对于单机部署,该字段总为空。 +* `version`: 节点的版本号,形如 `0.7.2` 的字符串。 +* `git_commit`: 节点编译的 git 版本号。 +* `start_time`: 节点的启动时间。 +* `uptime`: 节点的持续运行时间,形如 `24h 10m 59s 150ms` 的字符串。 +* `active_time`: 距离节点上一次活跃(也就是发送心跳请求)过去的时间,形如 `24h 10m 59s 150ms` 的字符串。单机模式下该字段总为空。 + + +尝试查询下这张表: + +```sql +SELECT * FROM CLUSTER_INFO; +``` + +一个单机模式的样例输出: + +```sql ++---------+------------+-----------+---------+------------+-------------------------+--------+-------------+ +| peer_id | peer_type | peer_addr | version | git_commit | start_time | uptime | active_time | ++---------+------------+-----------+---------+------------+-------------------------+--------+-------------+ +| 0 | STANDALONE | | 0.7.2 | 86ab3d9 | 2024-04-30T06:40:02.074 | 18ms | | ++---------+------------+-----------+---------+------------+-------------------------+--------+-------------+ +``` + +另一个输出来自一个分布式集群,它有三个 Datanode、一个 Frontend 和一个 Metasrv: + +```sql ++---------+-----------+----------------+---------+------------+-------------------------+----------+-------------+ +| peer_id | peer_type | peer_addr | version | git_commit | start_time | uptime | active_time | ++---------+-----------+----------------+---------+------------+-------------------------+----------+-------------+ +| 1 | DATANODE | 127.0.0.1:4101 | 0.7.2 | 86ab3d9 | 2024-04-30T06:40:04.791 | 4s 478ms | 1s 467ms | +| 2 | DATANODE | 127.0.0.1:4102 | 0.7.2 | 86ab3d9 | 2024-04-30T06:40:06.098 | 3s 171ms | 162ms | +| 3 | DATANODE | 127.0.0.1:4103 | 0.7.2 | 86ab3d9 | 2024-04-30T06:40:07.425 | 1s 844ms | 1s 839ms | +| -1 | FRONTEND | 127.0.0.1:4001 | 0.7.2 | 86ab3d9 | 2024-04-30T06:40:08.815 | 454ms | 47ms | +| 0 | METASRV | 127.0.0.1:3002 | unknown | unknown | | | | ++---------+-----------+----------------+---------+------------+-------------------------+----------+-------------+ +``` + + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/information-schema/collation-character-set-applicability.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/information-schema/collation-character-set-applicability.md similarity index 69% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/information-schema/collation-character-set-applicability.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/information-schema/collation-character-set-applicability.md index b6c8c38aa..40254eaf5 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/information-schema/collation-character-set-applicability.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/information-schema/collation-character-set-applicability.md @@ -1,3 +1,8 @@ +--- +keywords: [COLLATION_CHARACTER_SET_APPLICABILITY 表, 排序规则, 字符集, SQL 查询, 数据库适用性] +description: 介绍了 GreptimeDB 中排序规则与字符集的适用性,包括如何在 SQL 查询中使用这些规则和字符集。 +--- + # COLLATION_CHARACTER_SET_APPLICABILITY `COLLATION_CHARACTER_SET_APPLICABILITY` 表示了每个排序规则适用的字符集。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/information-schema/collations.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/information-schema/collations.md similarity index 80% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/information-schema/collations.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/information-schema/collations.md index 1bbf639ec..8b68d4ae6 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/information-schema/collations.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/information-schema/collations.md @@ -1,3 +1,8 @@ +--- +keywords: [COLLATIONS 表, 排序规则, 字符集, SQL 查询, 数据库排序] +description: 介绍了 GreptimeDB 中字符集的排序规则,包括排序规则的定义、使用方法和相关的 SQL 查询示例。 +--- + # COLLATIONS `COLLATIONS` 提供了每个字符集的排序规则信息。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/information-schema/columns.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/information-schema/columns.md similarity index 98% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/information-schema/columns.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/information-schema/columns.md index 5fe23ba34..0b2f1f0bb 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/information-schema/columns.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/information-schema/columns.md @@ -1,3 +1,8 @@ +--- +keywords: [COLUMNS 表, 列信息, SQL查询, 数据库列, 表结构] +description: COLUMNS 表提供关于表中每列的详细信息。 +--- + # COLUMNS `COLUMNS` 提供了关于表中每列的详细信息。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/information-schema/engines.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/information-schema/engines.md similarity index 84% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/information-schema/engines.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/information-schema/engines.md index a0adfd487..ee2a6bba6 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/information-schema/engines.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/information-schema/engines.md @@ -1,3 +1,8 @@ +--- +keywords: [存储引擎信息, ENGINES 表, 支持级别, 默认存储引擎, 事务支持] +description: ENGINES 表提供关于存储引擎的信息,检查 GreptimeDB 是否支持某个存储引擎或查看默认的存储引擎。 +--- + # ENGINES `ENGINES`表提供了关于存储引擎的信息。当你需要检查 GreptimeDB 是否支持某个存储引擎或者查看默认的存储引擎时,该表非常有用。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/information-schema/flows.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/information-schema/flows.md new file mode 100644 index 000000000..0fecad724 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/information-schema/flows.md @@ -0,0 +1,40 @@ +--- +keywords: [Flow 任务信息, FLOWS 表, 任务定义, 过期时间, 源表 id] +description: FLOWS 表提供 Flow 任务的相关信息。 +--- + +# FLOWS +`Flows` 表提供了 Flow 任务的相关信息。 + +```sql +DESC TABLE INFORMATION_SCHEMA.FLOWS; +``` + +```sql + Column | Type | Key | Null | Default | Semantic Type +------------------+--------+-----+------+---------+--------------- + flow_name | String | | NO | | FIELD + flow_id | UInt32 | | NO | | FIELD + table_catalog | String | | NO | | FIELD + flow_definition | String | | NO | | FIELD + comment | String | | YES | | FIELD + expire_after | Int64 | | YES | | FIELD + source_table_ids | String | | YES | | FIELD + sink_table_name | String | | NO | | FIELD + flownode_ids | String | | YES | | FIELD + options | String | | YES | | FIELD +(10 rows) +``` + +表中的列: + +* `flow_name`: Flow 任务的名称。 +* `flow_id`: Flow 任务的 id。 +* `table_catalog`: 该 Flow 所属的目录,命名为 `table_catalog` 以保持与 `INFORMATION_SCHEMA` 标准一致。 +* `flow_definition`: Flow 任务的定义,是用于创建 Flow 任务的 SQL 语句。 +* `comment`: Flow 任务的注释。 +* `expire_after`: Flow 任务的过期时间。 +* `source_table_ids`: Flow 任务的源表 id。 +* `sink_table_name`: Flow 任务的目标表名称。 +* `flownode_ids`: Flow 任务使用的 flownode id。 +* `options`: Flow 任务的其他额外选项。 \ No newline at end of file diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/information-schema/key-column-usage.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/information-schema/key-column-usage.md similarity index 95% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/information-schema/key-column-usage.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/information-schema/key-column-usage.md index ee2479e5a..ccb594c51 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/information-schema/key-column-usage.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/information-schema/key-column-usage.md @@ -1,3 +1,8 @@ +--- +keywords: [键约束, KEY_COLUMN_USAGE 表, 时间索引键, 外键约束, 列位置] +description: KEY_COLUMN_USAGE 表描述列的键约束,例如时间索引键的约束。 +--- + # KEY_COLUMN_USAGE `KEY_COLUMN_USAGE` 表描述列的键约束,例如时间索引键的约束。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/information-schema/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/information-schema/overview.md similarity index 76% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/information-schema/overview.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/information-schema/overview.md index 2eea1bb24..58c4f15a9 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/information-schema/overview.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/information-schema/overview.md @@ -1,3 +1,8 @@ +--- +keywords: [系统元数据, INFORMATION_SCHEMA, MySQL 兼容性, 自定义表, 集群信息] +description: INFORMATION_SCHEMA 提供对系统元数据的访问,例如数据库或表的名称、列的数据类型等。 +--- + # 概述 `INFORMATION_SCHEMA` 提供了对系统元数据的访问,例如数据库或表的名称、列的数据类型等。GreptimeDB 还提供了一些自定义的 `INFORMATION_SCHEMA` 表,用于查询有关 GreptimeDB 系统本身、集群信息和运行时指标等元数据。很多 `INFORMATION_SCHEMA` 表都有对应的 `SHOW` 命令,查询 `INFORMATION_SCHEMA` 的好处是可以在表之间进行连接。 @@ -41,15 +46,17 @@ | `USER_ATTRIBUTES` | 不支持。 | | `USER_PRIVILEGES` | 不支持。| | `VARIABLES_INFO` | 不支持。 | -| `VIEWS`| 不支持。 | - +| [`VIEWS`](./views.md)| 提供了当前用户可见的视图(View)列表及相关信息。 | +| [`TABLE_CONSTRAINTS`](./table-constraints.md) | 提供了主键、唯一索引和外键的信息。 | ## GreptimeDB 提供的表 |表名|描述| | --- | --- | | [`BUILD_INFO`](./build-info.md) | 提供了系统构建的信息。 | -| [`GREPTIME_REGION_PEERS`](./greptime-region-peers.md) | 提供了区域存储的详细信息。 | +| [`REGION_PEERS`](./region-peers.md) | 提供了表的 Region 存储的详细信息。 | +| [`REGION_STATISTICS`](./region-statistics.md) | 提供 Region 的详细统计信息,例如行数等。 | | [`RUNTIME_METRICS`](./runtime-metrics.md)| 提供了系统运行时指标。| - - \ No newline at end of file +| [`CLUSTER_INFO`](./cluster-info.md)| 提供了集群的节点拓扑信息。| +| [`FLOWS`](./flows.md) | 提供 Flow 相关信息。| +| [`PROCEDURE_INFO`](./procedure-info.md) | 提供 Procedure 相关信息。| diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/information-schema/partitions.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/information-schema/partitions.md similarity index 87% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/information-schema/partitions.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/information-schema/partitions.md index c64c61dd1..e1de3ae00 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/information-schema/partitions.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/information-schema/partitions.md @@ -1,3 +1,8 @@ +--- +keywords: [分区表信息, PARTITIONS 表, 分区方法, 分区表达式, Region Id] +description: PARTITIONS 表提供关于分区表的信息。 +--- + # PARTITIONS `PARTITIONS` 表提供了关于分区表的信息。 @@ -43,6 +48,19 @@ DESC PARTITIONS; 26 rows in set (0.01 sec) ``` +主要列包括: +* `table_catalog`:表所属目录的名称。该值始终为 `def`。 +* `table_schema`:表所属的 schema(数据库)的名称。 +* `table_name`:包含分区(region)的表的名称。 +* `partition_name`:分区(region)的名称。 +* `partition_ordinal_position`:所有分区按照定义的顺序进行索引,1 是分配给第一个分区的编号。 +* `partition_method`:该值始终为 `RANGE`,GreptimeDB 仅支持范围分区。 +* `partition_expression`:该分区的表达式。 +* `create_time`:分区创建的时间。 +* `greptime_partition_id`:GreptimeDB 扩展字段,也就是 Region Id。 + +创建一张分区表并查询: + ```sql CREATE TABLE public.test_p ( a INT PRIMARY KEY, @@ -54,9 +72,13 @@ PARTITION ON COLUMNS (a) ( a >= 10 AND a < 20, a >= 20 ); + +--- 查询表的分区信息--- SELECT * FROM PARTITIONS WHERE table_schema='public' AND table_name='test_p'\G ``` +示例输出如下: + ```sql *************************** 1. row *************************** table_catalog: greptime diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/information-schema/procedure-info.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/information-schema/procedure-info.md new file mode 100644 index 000000000..484589fa3 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/information-schema/procedure-info.md @@ -0,0 +1,37 @@ +--- +keywords: [Procedure 信息, PROCEDURE_INFO表, Procedure 类型, 时间戳, 锁定键] +description: PROCEDURE_INFO 表提供各种 Procedure 的详细信息。 +--- + +# PROCEDURE_INFO + +`PROCEDURE_INFO` 表提供了各种 Procedure 的详细信息。 +:::tip NOTE +该表在 [GreptimeCloud](https://greptime.cloud/) 中不可用。 +::: + +```sql +DESC TABLE INFORMATION_SCHEMA.PROCEDURE_INFO; +``` + +```sql ++----------------+----------------------+------+------+---------+---------------+ +| Column | Type | Key | Null | Default | Semantic Type | ++----------------+----------------------+------+------+---------+---------------+ +| procedure_id | String | | NO | | FIELD | +| procedure_type | String | | NO | | FIELD | +| start_time | TimestampMillisecond | | YES | | FIELD | +| end_time | TimestampMillisecond | | YES | | FIELD | +| status | String | | NO | | FIELD | +| lock_keys | String | | YES | | FIELD | ++----------------+----------------------+------+------+---------+---------------+ +``` + +`PROCEDURE_INFO` 表中的字段描述如下: + +- `procedure_id`: Procedure 的 ID。 +- `procedure_type`: Procedure 的类型。 +- `start_time`: Procedure 开始的时间戳。 +- `end_time`: Procedure 结束的时间戳。 +- `status`: Procedure 当前的状态。 +- `lock_keys`: Procedure 锁定的键。 \ No newline at end of file diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/information-schema/greptime-region-peers.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/information-schema/region-peers.md similarity index 75% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/information-schema/greptime-region-peers.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/information-schema/region-peers.md index c284ee749..88ebbed36 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/information-schema/greptime-region-peers.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/information-schema/region-peers.md @@ -1,6 +1,11 @@ -# GREPTIME_REGION_PEERS +--- +keywords: [Region 节点信息, REGION_PEERS 表, 节点状态, leader, learner] +description: REGION_PEERS 表显示 GreptimeDB 中单个 Region 节点的详细信息,例如它是 learner 还是 leader。 +--- -`GREPTIME_REGION_PEERS` 表显示了 GreptimeDB 中单个 Region 节点的详细信息,例如它是 learner 还是 leader。 +# REGION_PEERS + +`REGION_PEERS` 表显示了 GreptimeDB 中单个 Region 节点的详细信息,例如它是 learner 还是 leader。 :::tip 注意 该表在 [GreptimeCloud](https://greptime.cloud/) 中不可用。 @@ -8,7 +13,7 @@ ```sql USE INFORMATION_SCHEMA; -DESC GREPTIME_REGION_PEERS; +DESC REGION_PEERS; ``` 结果如下: @@ -27,7 +32,7 @@ DESC GREPTIME_REGION_PEERS; 6 rows in set (0.00 sec) ``` -`GREPTIME_REGION_PEERS` 表中的字段描述如下: +`REGION_PEERS` 表中的字段描述如下: - `region_id`:Region 的 ID。 - `peer_id`:Region peer 的 ID。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/information-schema/region-statistics.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/information-schema/region-statistics.md new file mode 100644 index 000000000..7dc56fa55 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/information-schema/region-statistics.md @@ -0,0 +1,67 @@ +--- +keywords: [Region 统计信息, REGION_STATISTICS 表, 总行数, 磁盘大小, 近似值] +description: REGION_STATISTICS 表提供关于某个 Region 统计信息的详细数据,包括总行数、磁盘大小等。 +--- + +# REGION_STATISTICS + +`REGION_STATISTICS` 表提供了关于某个 Region 统计信息的详细数据,包括总行数、磁盘大小等。这些统计信息都是近似值。 + +:::tip NOTE +此表在 [GreptimeCloud](https://greptime.cloud/) 中不可用。 +::: + +```sql +USE INFORMATION_SCHEMA; +DESC REGION_STATISTICS; +``` + +输出如下: + +```sql ++---------------+--------+------+------+---------+---------------+ +| Column | Type | Key | Null | Default | Semantic Type | ++---------------+--------+------+------+---------+---------------+ +| region_id | UInt64 | | NO | | FIELD | +| table_id | UInt32 | | NO | | FIELD | +| region_number | UInt32 | | NO | | FIELD | +| region_rows | UInt64 | | YES | | FIELD | +| disk_size | UInt64 | | YES | | FIELD | +| memtable_size | UInt64 | | YES | | FIELD | +| manifest_size | UInt64 | | YES | | FIELD | +| sst_size | UInt64 | | YES | | FIELD | +| index_size | UInt64 | | YES | | FIELD | +| engine | String | | YES | | FIELD | +| region_role | String | | YES | | FIELD | ++---------------+--------+------+------+---------+---------------+ +``` + +`REGION_STATISTICS` 表中的字段描述如下: + +- `region_id`: Region 的 ID。 +- `table_id`: 表的 ID。 +- `region_number`: Region 在表中的编号。 +- `region_rows`: Region 中的记录行数。 +- `disk_size`: Region 中数据文件的总大小,包括数据、索引及元信息等。 +- `memtable_size`: Region 中内存 memtables 的总大小。 +- `manifest_size`: Region 中元信息 manifest 文件的总大小。 +- `sst_size`: Region 中 SST 文件的总大小。 +- `index_size`: Region 中索引文件的总大小。 +- `engine`: Region 的引擎类型,可以是 `mito` 或 `metric`。 +- `region_role`: Region 的角色,可以是 `Leader` 或 `Follower`。 + +获取某张表的 Region 统计信息如下: + +```sql +SELECT r.* FROM REGION_STATISTICS r LEFT JOIN TABLES t on r.table_id = t.table_id \ +WHERE t.table_name = 'system_metrics'; +``` + +输出: +```sql ++---------------+----------+---------------+-------------+-----------+---------------+---------------+----------+------------+--------+-------------+ +| region_id | table_id | region_number | region_rows | disk_size | memtable_size | manifest_size | sst_size | index_size | engine | region_role | ++---------------+----------+---------------+-------------+-----------+---------------+---------------+----------+------------+--------+-------------+ +| 4398046511104 | 1024 | 0 | 8 | 4922 | 0 | 1338 | 3249 | 335 | mito | Leader | ++---------------+----------+---------------+-------------+-----------+---------------+---------------+----------+------------+--------+-------------+ +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/information-schema/runtime-metrics.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/information-schema/runtime-metrics.md similarity index 96% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/information-schema/runtime-metrics.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/information-schema/runtime-metrics.md index 841d47905..4ff9d0ffc 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/information-schema/runtime-metrics.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/information-schema/runtime-metrics.md @@ -1,3 +1,8 @@ +--- +keywords: [运行时指标, RUNTIME_METRICS 表, 系统指标, 集群指标, HTTP 端点] +description: RUNTIME_METRICS 表提供系统运行时指标,包括集群中 `/metrics` HTTP 端点输出的所有指标。 +--- + # RUNTIME_METRICS `RUNTIME_METRICS`表提供系统运行时指标。它包括集群中`/metrics` HTTP端点输出的所有指标。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/information-schema/schemata.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/information-schema/schemata.md similarity index 67% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/information-schema/schemata.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/information-schema/schemata.md index 30592eef0..a2aaf6d0e 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/information-schema/schemata.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/information-schema/schemata.md @@ -1,3 +1,8 @@ +--- +keywords: [数据库信息, SCHEMATA 表, SHOW DATABASES, 字段描述, 数据库目录] +description: SCHEMATA 表提供数据库的相关信息及其字段描述。 +--- + # SCHEMATA `SCHEMATA` 表提供数据库的相关信息。表数据等同于 `SHOW DATABASES` 语句的结果。 @@ -18,8 +23,8 @@ DESC SCHEMATA; | default_character_set_name | String | | NO | | FIELD | | default_collation_name | String | | NO | | FIELD | | sql_path | String | | YES | | FIELD | +| options | String | | YES | | FIELD | +----------------------------+--------+------+------+---------+---------------+ -5 rows in set (0.00 sec) ``` ```sql @@ -27,14 +32,14 @@ SELECT * FROM SCHEMATA; ``` ```sql -+--------------+--------------------+----------------------------+------------------------+----------+ -| catalog_name | schema_name | default_character_set_name | default_collation_name | sql_path | -+--------------+--------------------+----------------------------+------------------------+----------+ -| greptime | greptime_private | utf8 | utf8_bin | NULL | -| greptime | information_schema | utf8 | utf8_bin | NULL | -| greptime | public | utf8 | utf8_bin | NULL | -+--------------+--------------------+----------------------------+------------------------+----------+ -3 rows in set (0.01 sec) ++--------------+--------------------+----------------------------+------------------------+----------+-------------+ +| catalog_name | schema_name | default_character_set_name | default_collation_name | sql_path | options | ++--------------+--------------------+----------------------------+------------------------+----------+-------------+ +| greptime | greptime_private | utf8 | utf8_bin | NULL | | +| greptime | information_schema | utf8 | utf8_bin | NULL | | +| greptime | public | utf8 | utf8_bin | NULL | | +| greptime | test | utf8 | utf8_bin | NULL | ttl='7days' | ++--------------+--------------------+----------------------------+------------------------+----------+-------------+ ``` `SCHEMATA` 表中的字段描述如下: @@ -44,3 +49,4 @@ SELECT * FROM SCHEMATA; - `default_character_set_name`:数据库的默认字符集。 - `default_collation_name`:数据库的默认排序规则。 - `sql_path`:该项的值始终为 `NULL`。 +- `options`: GreptimeDB 扩展字段,数据库的配置参数。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/information-schema/table-constraints.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/information-schema/table-constraints.md new file mode 100644 index 000000000..f54907905 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/information-schema/table-constraints.md @@ -0,0 +1,60 @@ +--- +keywords: [表约束, TABLE_CONSTRAINTS 表, SQL 约束, 数据库约束, 约束类型, 约束描述] +description: TABLE_CONSTRAINTS 表描述了哪些表具有约束及相关信息。 +--- + +# TABLE_CONSTRAINTS + +`TABLE_CONSTRAINTS` 表描述了哪些表具有约束(constraint)以及相关信息。 + +```sql +DESC INFORMATION_SCHEMA.table_constraints; +``` + +```sql ++--------------------+--------+------+------+---------+---------------+ +| Column | Type | Key | Null | Default | Semantic Type | ++--------------------+--------+------+------+---------+---------------+ +| constraint_catalog | String | | NO | | FIELD | +| constraint_schema | String | | NO | | FIELD | +| constraint_name | String | | NO | | FIELD | +| table_schema | String | | NO | | FIELD | +| table_name | String | | NO | | FIELD | +| constraint_type | String | | NO | | FIELD | +| enforced | String | | NO | | FIELD | ++--------------------+--------+------+------+---------+---------------+ +``` + +表中的列: + +* `CONSTRAINT_CATALOG`: 约束所属 catalog 的名称。此值始终为 `def`。 +* `CONSTRAINT_SCHEMA`: 约束所属数据库的名称。 +* `CONSTRAINT_NAME`: 约束的名称,可以是 `TIME INDEX` 或 `PRIMARY`。 +* `TABLE_NAME`: 表的名称。 +* `CONSTRAINT_TYPE`: 约束的类型。值可以是 `TIME INDEX` 或 `PRIMARY KEY`。`TIME INDEX` 和 `PRIMARY KEY` 信息类似于 `SHOW INDEX` 语句的执行结果。 +* `enforced`: 不支持 `CHECK` 约束,此值始终为 `YES`。 + +```sql +select * from INFORMATION_SCHEMA.table_constraints WHERE table_name = 'monitor'\G; +``` + +输出结果: + +```sql +*************************** 1. row *************************** +constraint_catalog: def + constraint_schema: public + constraint_name: TIME INDEX + table_schema: public + table_name: monitor + constraint_type: TIME INDEX + enforced: YES +*************************** 2. row *************************** +constraint_catalog: def + constraint_schema: public + constraint_name: PRIMARY + table_schema: public + table_name: monitor + constraint_type: PRIMARY KEY + enforced: YES +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/information-schema/tables.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/information-schema/tables.md new file mode 100644 index 000000000..468b8cdc6 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/information-schema/tables.md @@ -0,0 +1,114 @@ +--- +keywords: [表信息, TABLES 表, SQL 表, 数据库表, 表字段, 表描述] +description: TABLES 表提供数据库中表的信息及其字段描述。 +--- + +# TABLES + +`TABLES` 表提供数据库中表的信息: + +```sql +USE INFORMATION_SCHEMA; +DESC TABLES; +``` + +结果如下: + +```sql ++------------------+----------+------+------+---------+---------------+ +| Column | Type | Key | Null | Default | Semantic Type | ++------------------+----------+------+------+---------+---------------+ +| table_catalog | String | | NO | | FIELD | +| table_schema | String | | NO | | FIELD | +| table_name | String | | NO | | FIELD | +| table_type | String | | NO | | FIELD | +| table_id | UInt32 | | YES | | FIELD | +| data_length | UInt64 | | YES | | FIELD | +| max_data_length | UInt64 | | YES | | FIELD | +| index_length | UInt64 | | YES | | FIELD | +| max_index_length | UInt64 | | YES | | FIELD | +| avg_row_length | UInt64 | | YES | | FIELD | +| engine | String | | YES | | FIELD | +| version | UInt64 | | YES | | FIELD | +| row_format | String | | YES | | FIELD | +| table_rows | UInt64 | | YES | | FIELD | +| data_free | UInt64 | | YES | | FIELD | +| auto_increment | UInt64 | | YES | | FIELD | +| create_time | DateTime | | YES | | FIELD | +| update_time | DateTime | | YES | | FIELD | +| check_time | DateTime | | YES | | FIELD | +| table_collation | String | | YES | | FIELD | +| checksum | UInt64 | | YES | | FIELD | +| create_options | String | | YES | | FIELD | +| table_comment | String | | YES | | FIELD | +| temporary | String | | YES | | FIELD | ++------------------+----------+------+------+---------+---------------+ +``` + +```sql +SELECT * FROM tables WHERE table_schema='public' AND table_name='monitor'\G +``` + +```sql +*************************** 1. row *************************** + table_catalog: greptime + table_schema: public + table_name: monitor + table_type: BASE TABLE + table_id: 1054 + data_length: 0 + max_data_length: 0 + index_length: 0 +max_index_length: 0 + avg_row_length: 0 + engine: mito + version: 11 + row_format: Fixed + table_rows: 0 + data_free: 0 + auto_increment: 0 + create_time: 2024-07-24 22:06:18.085000 + update_time: NULL + check_time: NULL + table_collation: NULL + checksum: 0 + create_options: + table_comment: NULL + temporary: N +1 row in set (0.01 sec) +``` + + +下方的语句是等价的: + +```sql +SELECT table_name FROM INFORMATION_SCHEMA.TABLES + WHERE table_schema = '' + [AND table_name LIKE 'monitor'] + +SHOW TABLES + FROM db_name + [LIKE 'monitor'] +``` + +`TABLES` 表的字段描述如下: + +- `table_catalog`:表所属的目录。该值始终为 `greptime`。 +- `table_schema`:表所属的数据库。 +- `table_name`:表的名称。 +- `table_type`:表的类型。 + - `BASE TABLE`:基础表 + - `TEMPORARY`:临时结果集 + - `VIEW`:视图表 +- `table_id`:表 ID。 +- `data_length`: 表中 SST 文件的总长度(以字节为单位),近似值。 +- `index_length`: 表中索引文件的总长度(以字节为单位),近似值。 +- `table_rows`: 表中总的记录行数,近似值。 +- `avg_row_length`: 表中记录的平均大小(以字节为单位),近似值。 +- `engine`:该表使用的存储引擎。 +- `version`: 版本。固定值为 `11`。 +- `create_time`: 表创建的时间戳。 +- `table_comment`: 表的注释。 +- 其他列如 `table_rows`, `row_format` 等不支持,仅用于兼容 MySQL。GreptimeDB 未来可能会支持其中的一些列。 + + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/information-schema/views.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/information-schema/views.md new file mode 100644 index 000000000..7789bbd64 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/information-schema/views.md @@ -0,0 +1,42 @@ +--- +keywords: [视图, VIEWS 表, SQL 视图, 数据库视图, 视图定义, 视图字段] +description: VIEWS 表提供当前用户可见的视图列表及其字段描述。 +--- + +# VIEWS + +`VIEWS` 表提供了当前用户可见的视图(View)列表。 + +```sql +DESC TABLE INFORMATION_SCHEMA.VIEWS; +``` + +```sql ++----------------------+---------+------+------+---------+---------------+ +| Column | Type | Key | Null | Default | Semantic Type | ++----------------------+---------+------+------+---------+---------------+ +| table_catalog | String | | NO | | FIELD | +| table_schema | String | | NO | | FIELD | +| table_name | String | | NO | | FIELD | +| view_definition | String | | NO | | FIELD | +| check_option | String | | YES | | FIELD | +| is_updatable | Boolean | | YES | | FIELD | +| definer | String | | YES | | FIELD | +| security_type | String | | YES | | FIELD | +| character_set_client | String | | YES | | FIELD | +| collation_connection | String | | YES | | FIELD | ++----------------------+---------+------+------+---------+---------------+ +``` + +表中的列: + +* `table_catalog`: 视图所属 catalog 的名称。 +* `table_schema`: 视图所属数据库的名称。 +* `table_name`: 视图名称。 +* `view_definition`: 视图的定义,即创建视图时的 `SELECT` 语句。 +* `check_option`: 不支持,始终为 `NULL`。 +* `is_updatable`: 视图是否可以进行 `UPDATE/INSERT/DELETE` 操作,始终为 `NO`。 +* `definer`: 创建视图的用户的名称。 +* `security_type`: 不支持,始终为 `NULL`。 +* `character_set_client`: 创建视图时 `character_set_client` 会话变量的值,始终为 `utf8`。 +* `collation_connection`: 创建视图时 `collation_connection` 会话变量的值,始终为 `utf8_bin`。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/insert.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/insert.md similarity index 94% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/insert.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/insert.md index a9e9f45ac..243e0bbfb 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/insert.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/insert.md @@ -1,3 +1,8 @@ +--- +keywords: [SQL INSERT 语句, 插入数据, 多条记录插入, 默认值插入, 二进制数据插入, 特殊数值插入] +description: INSERT 用于将一条或多条记录插入到 GreptimeDB 中的表中,支持指定列名和使用默认值。 +--- + # INSERT `INSERT` 用于将一条或多条记录插入到 GreptimeDB 中的表中。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/join.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/join.md similarity index 82% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/join.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/join.md index 781e0b50d..457c540ac 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/join.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/join.md @@ -1,3 +1,8 @@ +--- +keywords: [SQL JOIN 子句, 表连接, INNER JOIN, LEFT JOIN, RIGHT JOIN, FULL OUTER JOIN, SQL 示例] +description: JOIN 用于组合两个或多个表中基于相关列的行,支持 INNER JOIN、LEFT JOIN、RIGHT JOIN 和 FULL OUTER JOIN。 +--- + # JOIN `JOIN` 用于组合两个或多个表中基于相关列的行。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/limit.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/limit.md similarity index 90% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/limit.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/limit.md index aad616320..9b48d0325 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/limit.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/limit.md @@ -1,3 +1,8 @@ +--- +keywords: [SQL LIMIT 子句, 查询行数限制, SQL 性能优化, 数据库查询优化, SQL 示例] +description: 介绍了 `LIMIT` 子句的用法,通过示例展示了如何限制查询返回的行数。 +--- + # LIMIT `LIMIT` 用于限制查询返回的行数。当处理大数据集时该子句特别有用,因为它通过减少需要处理的数据量来提高查询性能。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/order_by.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/order_by.md similarity index 93% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/order_by.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/order_by.md index 833c26bd4..f7b06609a 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/order_by.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/order_by.md @@ -1,3 +1,8 @@ +--- +keywords: [ORDER BY 语法, 数据排序, 升序排序, 降序排序, SQL 示例] +description: 介绍了 `ORDER BY` 语法的基本用法,通过示例展示了如何对数据进行升序或降序排序。 +--- + # ORDER BY `ORDER BY` 语法用于根据 `SELECT` 语句中的一个或多个列对数据进行升序或降序排序。 diff --git a/versioned_docs/version-0.7/reference/sql/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/overview.md similarity index 72% rename from versioned_docs/version-0.7/reference/sql/overview.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/overview.md index 5d13ce2f8..8d5fa9fc7 100644 --- a/versioned_docs/version-0.7/reference/sql/overview.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/overview.md @@ -1,8 +1,10 @@ -# SQL +# 概述 +* [数据类型](./data-types) * [INSERT](./insert.md) * [CAST](./cast.md) * [COPY](./copy.md) +* [DROP](./drop.md) * [SELECT](./select.md) * [DISTINCT](./distinct.md) * [WHERE](./where.md) @@ -10,13 +12,17 @@ * [GROUP BY](./group_by.md) * [LIMIT](./limit.md) * [JOIN](./join.md) -* [Functions](./functions.md) +* [RANGE](./range.md) * [DELETE](./delete.md) * [SHOW](./show.md) * [TQL](./tql.md) +* [TRUNCATE](./truncate.md) * [CREATE](./create.md) * [DESCRIBE TABLE](./describe_table.md) +* [WITH](./with.md) * [ALTER](./alter.md) * [EXPLAIN](./explain.md) +* [Functions](./functions/overview.md) +* [ADMIN](./admin.md) * [ANSI Compatibility](./compatibility.md) * [INFORMATION_SCHEMA](./information-schema/overview.md) diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/range.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/range.md similarity index 98% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/range.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/range.md index 94467518c..abeb3a1c1 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/range.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/range.md @@ -1,3 +1,8 @@ +--- +keywords: [Range 查询, 时间范围查询, 聚合查询, SQL 示例, FILL 选项] +description: 介绍了 Range 查询的语法和用法,包括 `FILL`、`TO` 和 `BY` 选项的详细说明和示例。 +--- + # RANGE QUERY 查询并聚合一个给定长度的时间范围的数据是时序数据常见的一种查询模式,例如 `PromQL` 中的 `Range selector`。而 GreptimeDB 在 SQL 中支持了 Range 查询,用于将时序数据汇总为时间块,并在时间块上进行数据的聚合。Range 查询作为 `SELECT` 语句的一部分,可与 SQL 灵活结合,从而在 SQL 中提供更强大的时序数据查询能力。 @@ -25,7 +30,7 @@ INTERVAL := TIME_INTERVAL | ( INTERVAL expr ) - 子关键字 `BY` ,可选字段,后接参数 `(columna, columnb,..)` ,描述了聚合键。详情请见[BY OPTION](#by-option)。 - 参数 `INTERVAL` ,主要用于给出一段时间长度,有两种参数形式: - 基于 `PromQL Time Durations` 格式的字符串(例如:`3h`、`1h30m`)。访问 [Prometheus 文档](https://prometheus.io/docs/prometheus/latest/querying/basics/#time-durations) 获取该格式更详细的说明。 - - `Interval` 类型,使用 `Interval` 类型需要携带括号,(例如:`(INTERVAL '1 year 3 hours 20 minutes')`)。访问 [Interval](./functions.md#interval) 获取该格式更详细的说明。 + - `Interval` 类型,使用 `Interval` 类型需要携带括号,(例如:`(INTERVAL '1 year 3 hours 20 minutes')`)。访问 [Interval](./data-types.md#interval-type) 获取该格式更详细的说明。 - `AGGR_FUNCTION(column1, column2,..) RANGE INTERVAL [FILL FILL_OPTION]` 称为一个 Range 表达式。 - `AGGR_FUNCTION(column1, column2,..)` 是一个聚合函数,代表需要聚合的表达式。 - 关键字 `RANGE`,必选字段,后接参数 `INTERVAL` 指定了每次数据聚合的时间范围, @@ -217,7 +222,7 @@ ALIGN '5s'; `TO` 选项、`RANGE` 选项和 `ALIGN INTERVAL` 共同决定了范围查询的时间窗口。 请参考[时间范围窗口](/user-guide/query-data/sql.md#时间范围窗口)。 -`TO` 选项的默认值为当前查询客户端的时区。如果想要设置时区,请参考 [MySQL 客户端](../../user-guide/clients/mysql.md#时区) 或 [PostgreSQL 客户端](../../user-guide/clients/postgresql.md#时区)文档中的时区设置。其他可用的 `TO` 选项有: +`TO` 选项的默认值为当前查询客户端的时区。如果想要设置时区,请参考 [MySQL 客户端](/user-guide/protocols/mysql.md#时区) 或 [PostgreSQL 客户端](/user-guide/protocols/postgresql.md#时区)文档中的时区设置。其他可用的 `TO` 选项有: | TO | 描述 | | :---------: | :----------------------------------------------------------------: | diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/select.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/select.md similarity index 92% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/select.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/select.md index 8a612d6e8..4c1a23f75 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/select.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/select.md @@ -1,3 +1,8 @@ +--- +keywords: [SELECT 语句, SQL 查询, WHERE 子句, LIMIT 子句, JOIN 子句, GROUP BY 子句] +description: 介绍了 `SELECT` 语句的基本语法和用法,包括 `WHERE`、`LIMIT`、`JOIN` 和 `GROUP BY` 子句的示例。 +--- + # SELECT `SELECT` 语句允许你从一个或多个表中选择列。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/show.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/show.md new file mode 100644 index 000000000..a69146a70 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/show.md @@ -0,0 +1,386 @@ +--- +keywords: [SHOW 关键字, 数据库信息, 表信息, SQL 示例, SHOW DATABASES] +description: 介绍了 `SHOW` 关键字的各种用法,包括展示数据库、表、视图和索引等信息的语法和示例。 +--- + +# SHOW + +`SHOW` 关键字提供数据库和表信息。 + +## SHOW DATABASES + +展示所有数据库: + +```sql +SHOW [FULL] DATABASES; +``` + +```sql ++---------+ +| Schemas | ++---------+ +| public | ++---------+ +1 row in set (0.01 sec) +``` + +展示名称符合 `LIKE` 模式的数据库: + +```sql +SHOW DATABASES LIKE 'p%'; +``` + +根据 `where` 表达式展示数据库: + +```sql +SHOW DATABASES WHERE Schemas='test_public_schema'; +``` + +展示所有数据库,包括它们的选项: + +```sql +CREATE DATABASE test WITH(ttl='7d'); +SHOW FULL DATABASES; +``` + +```sql ++--------------------+-------------+ +| Database | Options | ++--------------------+-------------+ +| greptime_private | | +| information_schema | | +| public | | +| test | ttl='7days' | ++--------------------+-------------+ +``` + +## SHOW CREATE DATABASE + +展示创建指定数据库的 `CREATE DATABASE` 语句: + +```sql +SHOW CREATE DATABASE test; +``` + +```sql ++----------+------------------------------------------------------------+ +| Database | Create Database | ++----------+------------------------------------------------------------+ +| test | CREATE DATABASE IF NOT EXISTS test +WITH( + ttl = '7days' +) | ++----------+------------------------------------------------------------+ +1 row in set (0.01 sec) +``` + +## SHOW TABLES + +展示所有表: + +```sql +SHOW TABLES; +``` + +```sql ++---------+ +| Tables | ++---------+ +| numbers | +| scripts | ++---------+ +2 rows in set (0.00 sec) +``` + +展示 `test` 数据库中的所有表: + +```sql +SHOW TABLES FROM test; +``` + +展示名称符合 `LIKE` 模式的表: + +```sql +SHOW TABLES like '%prometheus%'; +``` + +根据 `where` 表达式展示表: + +```sql +SHOW TABLES FROM test WHERE Tables='numbers'; +``` + +## SHOW FULL TABLES + +```sql +SHOW FULL TABLES [IN | FROM] [DATABASE] [LIKE pattern] [WHERE query] +``` + +将会展示指定数据库(或者默认 `public`)中所有的表及其类型: + +```sql +SHOW FULL TABLES; +``` + +```sql ++---------+------------+ +| Tables | Table_type | ++---------+------------+ +| monitor | BASE TABLE | +| numbers | TEMPORARY | ++---------+------------+ +2 rows in set (0.00 sec) +``` + +* `Tables`: 表的名称 +* `Table_type`: 表的类型,例如 `BASE_TABLE`, `TEMPORARY` 和 `VIEW` 等等。 + +同样也支持 `like` 和 `where` 查询: + +```sql +SHOW FULL TABLES FROM public like '%mo%'; +``` + +```sql ++---------+------------+ +| Tables | Table_type | ++---------+------------+ +| monitor | BASE TABLE | ++---------+------------+ +1 row in set (0.01 sec) +``` + +```sql +SHOW FULL TABLES WHERE Table_type='BASE TABLE'; +``` + +```sql ++---------+------------+ +| Tables | Table_type | ++---------+------------+ +| monitor | BASE TABLE | ++---------+------------+ +1 row in set (0.01 sec) +``` + +## SHOW CREATE TABLE + +展示创建指定表的 `CREATE TABLE` 语句: + +```sql +SHOW CREATE TABLE [table] +``` + +例如: + +```sql +SHOW CREATE TABLE system_metrics; +``` + +```sql ++----------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| Table | Create Table | ++----------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| system_metrics | CREATE TABLE IF NOT EXISTS `system_metrics` ( + `host` STRING NULL, + `idc` STRING NULL, + `cpu_util` DOUBLE NULL, + `memory_util` DOUBLE NULL, + `disk_util` DOUBLE NULL, + `ts` TIMESTAMP(3) NOT NULL DEFAULT current_timestamp(), + TIME INDEX (`ts`), + PRIMARY KEY (`host`, `idc`) +) + +ENGINE=mito +WITH( + regions = 1 +) | ++----------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +``` + +* `Table`: 表的名称 +* `Create Table`: 用于创建该表的 SQL + +## SHOW CREATE FLOW + +展示创建指定 Flow 任务的 `CREATE FLOW` 语句。 + +比如: + +```sql +public=> SHOW CREATE FLOW filter_numbers; +``` + +```sql + Flow | Create Flow +----------------+------------------------------------------------------- + filter_numbers | CREATE OR REPLACE FLOW IF NOT EXISTS filter_numbers + + | SINK TO out_num_cnt + + | AS SELECT number FROM numbers_input WHERE number > 10 +(1 row) +``` + +## SHOW FLOWS + +展示当前所有 Flow 任务: + +```sql +public=> SHOW FLOWS; +``` + +```sql + Flows +---------------- + filter_numbers +(1 row) +``` + +同样也支持 `LIKE` 表达式: +```sql +public=> show flows like "filter%"; +``` + +```sql + Flows +---------------- + filter_numbers +(1 row) +``` + +## SHOW CREATE VIEW + +用于显示视图(View)的定义: + +```sql +SHOW CREATE VIEW cpu_monitor; +``` + +``` ++-------------+--------------------------------------------------------------+ +| View | Create View | ++-------------+--------------------------------------------------------------+ +| cpu_monitor | CREATE VIEW cpu_monitor AS SELECT cpu, host, ts FROM monitor | ++-------------+--------------------------------------------------------------+ +``` + +## SHOW VIEWS + +列出所有视图: + +```sql +SHOW VIEWS; +``` + +```sql ++----------------+ +| Views | ++----------------+ +| cpu_monitor | +| memory_monitor | ++----------------+ +``` + +当然,它也支持 `LIKE` 查询: + +```sql +SHOW VIEWS LIKE 'cpu%'; +``` + +```sql ++-------------+ +| Views | ++-------------+ +| cpu_monitor | ++-------------+ +``` + +以及 `WHERE` 条件: + +```sql +SHOW VIEWS WHERE Views = 'memory_monitor'; +``` + +```sql ++----------------+ +| Views | ++----------------+ +| memory_monitor | ++----------------+ +``` + +## SHOW 语句的扩展 + +与 MySQL 类似,一些 `SHOW` 语句的扩展伴随着 [`INFORMATION_SCHEMA`](/reference/sql/information-schema/overview.md) 的实现,它们还接受 `WHERE` 子句,提供了在指定显示的行时更大的灵活性。 + +GreptimeDB 为 MySQL 兼容性实现了这些扩展的一部分,这对于像 [Navicat for MySQL](https://www.navicat.com/en/products/navicat-for-mysql) 或 [dbeaver](https://dbeaver.io/) 这样的工具连接 GreptimeDB 非常有用。 + +```sql +SHOW CHARACTER SET; +``` + +输出类似于 `INFORMATION_SCHEMA.CHARACTER_SETS` 表: + +```sql ++---------+---------------+-------------------+--------+ +| Charset | Description | Default collation | Maxlen | ++---------+---------------+-------------------+--------+ +| utf8 | UTF-8 Unicode | utf8_bin | 4 | ++---------+---------------+-------------------+--------+ +``` + +使用 `SHOW COLLATION` 来查看 `INFORMATION_SCHEMA.COLLATIONS` 表。 + +```sql +SHOW INDEX FROM monitor; +``` + +列出表中的所有索引: + +```sql ++---------+------------+------------+--------------+-------------+-----------+-------------+----------+--------+------+----------------------------+---------+---------------+---------+------------+ +| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment | Visible | Expression | ++---------+------------+------------+--------------+-------------+-----------+-------------+----------+--------+------+----------------------------+---------+---------------+---------+------------+ +| monitor | 1 | PRIMARY | 1 | host | A | NULL | NULL | NULL | YES | greptime-inverted-index-v1 | | | YES | NULL | +| monitor | 1 | TIME INDEX | 1 | ts | A | NULL | NULL | NULL | NO | greptime-inverted-index-v1 | | | YES | NULL | ++---------+------------+------------+--------------+-------------+-----------+-------------+----------+--------+------+----------------------------+---------+---------------+---------+------------+ +``` + +这是 `INFORMATION_SCHEMA.TABLE_CONSTRAINTS` 的扩展。 + +列出表中的所有列: + +```sql +SHOW COLUMNS FROM monitor; +``` + +输出类似于 `INFORMATION_SCHEMA.COLUMNS`: + +```sql ++--------+--------------+------+------------+---------------------+-------+----------------------+ +| Field | Type | Null | Key | Default | Extra | Greptime_type | ++--------+--------------+------+------------+---------------------+-------+----------------------+ +| cpu | double | Yes | | 0 | | Float64 | +| host | string | Yes | PRI | NULL | | String | +| memory | double | Yes | | NULL | | Float64 | +| ts | timestamp(3) | No | TIME INDEX | current_timestamp() | | TimestampMillisecond | ++--------+--------------+------+------------+---------------------+-------+----------------------+ +``` + +所有这些 `SHOW` 扩展都接受 `WHERE` 子句: + +```sql +SHOW COLUMNS FROM monitor WHERE Field = 'cpu'; +``` + +```sql ++-------+--------+------+------+---------+-------+---------------+ +| Field | Type | Null | Key | Default | Extra | Greptime_type | ++-------+--------+------+------+---------+-------+---------------+ +| cpu | double | Yes | | 0 | | Float64 | ++-------+--------+------+------+---------+-------+---------------+ +``` + +其他 `SHOW` 扩展语句: +* `SHOW STATUS` 和 `SHOW VARIABLES` 不支持,仅返回空结果。 +* `SHOW TABLE STATUS` 是 `INFORMATION_SCHEMA.TABLES` 的扩展。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/tql.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/tql.md similarity index 98% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/tql.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/tql.md index ace85efca..94a25249f 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/tql.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/tql.md @@ -1,3 +1,8 @@ +--- +keywords: [TQL 关键字, EVAL, EXPLAIN, ANALYZE, 时间序列查询] +description: 介绍了 `TQL` 关键字及其在 GreptimeDB 中的用法,包括 `EVAL`、`EXPLAIN` 和 `ANALYZE` 的语法和示例。 +--- + # TQL `TQL` 关键字在 SQL 中执行 TQL 语言。TQL 是 Time-Series Query Language 的缩写,是 GreptimeDB 中对 Prometheus 的 [PromQL](https://prometheus.io/docs/prometheus/latest/querying/basics/) 的扩展。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/truncate.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/truncate.md new file mode 100644 index 000000000..3429db8d1 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/truncate.md @@ -0,0 +1,16 @@ +--- +keywords: [TRUNCATE TABLE, SQL 删除, 高效删除, 数据库操作, SQL 示例] +description: 介绍了 `TRUNCATE TABLE` 语句的用法,用于高效地删除表中的所有数据。 +--- + +# TRUNCATE + +`TRUNCATE TABLE table` 语句用于删除表中的所有数据。它比 `DELETE FROM table` 高效得多。 + +```sql +TRUNCATE TABLE monitor; +``` + +```sql +Query OK, 0 rows affected (0.02 sec) +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/where.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/where.md similarity index 85% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/where.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/where.md index 1e562e9ca..901ac3ae1 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/sql/where.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/where.md @@ -1,3 +1,8 @@ +--- +keywords: [WHERE 子句, SQL 过滤, 逻辑运算符, 数字比较, 列表查找] +description: 介绍了 `WHERE` 子句的用法,包括逻辑运算符、数字比较和列表查找的示例。 +--- + # WHERE `WHERE` 子句允许通过指定条件过滤数据。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/with.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/with.md new file mode 100644 index 000000000..8a77d795c --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/sql/with.md @@ -0,0 +1,89 @@ +--- +keywords: [公共表表达式, CTE, SQL 查询, WITH 关键字, SQL 示例] +description: 介绍了如何使用 `WITH` 关键字定义公共表表达式(CTE),包括基本语法和示例。 +--- + +# WITH + +使用 `WITH` 来指定一个公共表表达式(CTE)。 + +## 什么是公共表表达式(CTE)? + +公共表表达式(CTE)是一个可以在 `SELECT`、`INSERT`、`UPDATE` 或 `DELETE` 语句中引用的临时结果集。CTE 有助于将复杂的查询分解成更易读的部分,并且可以在同一个查询中多次引用。 + +## CTE 的基本语法 + +CTE 通常使用 `WITH` 关键字定义。基本语法如下: + +```sql +WITH cte_name [(column1, column2, ...)] AS ( + QUERY +) +SELECT ... +FROM cte_name; +``` + +## 示例 + +### 非递归 CTE + +```sql +WITH cte AS (SELECT number FROM numbers LIMIT 2) SELECT * FROM cte t1, cte t2; +``` + +```sql ++--------+--------+ +| number | number | ++--------+--------+ +| 0 | 0 | +| 0 | 1 | +| 1 | 0 | +| 1 | 1 | ++--------+--------+ +``` + +如果 CTE 名称后面有一个括起来的名称列表,这些名称就是 CTE 的列名,可以在查询里使用: + +```sql +WITH cte (col1, col2) AS +( + SELECT 1, 2 + UNION ALL + SELECT 3, 4 +) +SELECT col1, col2 FROM cte; +``` + +列表中的名称数量必须与结果集中的列数相同。 + +```sql ++------+------+ +| col1 | col2 | ++------+------+ +| 1 | 2 | +| 3 | 4 | ++------+------+ +``` + +联合查询两个 CTE: + +```sql +WITH + cte1 AS (SELECT number AS a FROM NUMBERS LIMIT 2), + cte2 AS (SELECT number AS b FROM NUMBERS LIMIT 2) +SELECT * FROM cte1 JOIN cte2 +ON cte1.a = cte2.b; +``` + +```sql ++------+------+ +| a | b | ++------+------+ +| 1 | 1 | +| 0 | 0 | ++------+------+ +``` + +### 递归 CTE + +递归 CTE 目前尚未实现。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/telemetry.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/telemetry.md similarity index 87% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/telemetry.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/telemetry.md index 4190d6ebc..ba76aeafb 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/reference/telemetry.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/telemetry.md @@ -1,3 +1,8 @@ +--- +keywords: [指标收集, 数据收集, 隐私保护, 配置管理, 禁用指标, 操作系统, 机器架构, 集群信息] +description: 介绍 GreptimeDB 的指标收集功能,包括收集的数据类型、如何禁用指标收集等内容。 +--- + # 指标收集 为了提升我们的服务,GreptimeDB 会收集一些数据,包括 GreptimeDB 版本、节点数量、使用的操作系统、环境架构以及类似的技术细节等信息。但是我们尊重您的隐私,并确保不收集任何特定于用户的数据,其中包括数据库名称、表名称、查询内容等。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/time-durations.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/time-durations.md new file mode 100644 index 000000000..ec32d8ad7 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/reference/time-durations.md @@ -0,0 +1,46 @@ +--- +keywords: [时间范围, 时间跨度, 时间单位] +description: 了解 GreptimeDB 中时间范围对象的表示方法,包括支持的时间单位和示例。 +--- + +# 时间范围对象 + +GreptimeDB 使用时间范围对象来表示各种上下文中的时间跨度, +包括 SQL 查询、配置文件和 API 请求。 +时间持续时间表示为由连接的时间跨度组成的字符串, +每个时间跨度由一个十进制数字序列和一个单位后缀表示。 +这些后缀不区分大小写,并且支持单数和复数形式。例如,`1hour 12min 5s`。 + +每个时间跨度由一个整数和一个后缀组成。支持的后缀有: + +- `nsec`, `ns`: 纳秒 +- `usec`, `us`: 微秒 +- `msec`, `ms`: 毫秒 +- `seconds`, `second`, `sec`, `s`: 秒 +- `minutes`, `minute`, `min`, `m`: 分钟 +- `hours`, `hour`, `hr`, `h`: 小时 +- `days`, `day`, `d`: 天 +- `weeks`, `week`, `w`: 周 +- `months`, `month`, `M`: 定义为 30.44 天 +- `years`, `year`, `y`: 定义为 365.25 天 + +在十进制整数后附加上述单位之一,表示等值的秒数。 +例如: + +- `1s`: 等效于 1 秒 +- `2m`: 等效于 120 秒 +- `1ms`: 等效于 0.001 秒 +- `2h`: 等效于 7200 秒 + +以下写法无效: + +- `0xABm`: 不支持十六进制数字 +- `1.5h`: 不支持浮点数 +- `+Infd`: 不支持 `±Inf` 或 `NaN` 值 + +以下是一些有效的时间范围示例: + +- `1h`: 一小时 +- `1h30m`, `1h 30m`: 一小时三十分钟 +- `1h30m10s`, `1h 30m 10s`: 一小时三十分钟十秒 + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/administration/capacity-plan.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/administration/capacity-plan.md new file mode 100644 index 000000000..55a0627b7 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/administration/capacity-plan.md @@ -0,0 +1,71 @@ +--- +keywords: [容量规划, CPU 需求, 内存需求, 存储需求, 数据保留策略, 硬件成本, 资源分配, 性能优化] +description: 提供 GreptimeDB 的 CPU、内存和存储需求的一般建议,帮助用户根据工作负载进行容量规划。 +--- + +# 容量规划 + +本指南提供了关于 GreptimeDB 的 CPU、内存和存储需求的一般建议。 + +GreptimeDB 具备超轻量级的启动基准, +这使数据库能以最少的服务器资源启动。 +然而当为生产环境配置服务器容量时, +以下关键因素需要被考虑: + +- 每秒处理的数据点数 +- 每秒查询请求 +- 数据量 +- 数据保留策略 +- 硬件成本 + +要监控 GreptimeDB 的各种指标,请参阅[监控](/user-guide/administration/monitoring/export-metrics.md)。 + +## CPU + +一般来说,大量并发查询、处理大量数据或执行其他计算密集型操作的应用需要更多的 CPU 核数。 + +以下是一些关于 CPU 资源使用的建议, +但实际使用的 CPU 核数取决于你实际的工作负载。 + +你可以考虑将 30% 的 CPU 资源用于数据写入, +剩余 70% 用于查询和分析。 + +一般推荐 CPU 到内存的比例为 1:4(例如,8 核 32 GB), +如果你的主要工作负载是数据写入且查询请求较少, +1:2 的比例(8 核 16 GB)也是可以接受的。 + +## 内存 + +一般来说,内存越大,查询速度越快。 +对于基本工作负载,建议至少有 8 GB 的内存,对于更高级的工作负载,建议至少有 32 GB 的内存。 + +## 存储空间 + +GreptimeDB 具有高效的数据压缩机制,可将原始数据大小减少到其初始大小的约 1/8 到 1/10。 +这使得 GreptimeDB 以更小的空间存储大量数据。 + +数据可以存储在本地文件系统或云存储中,例如 AWS S3。 +有关存储选项的更多信息, +请参阅[存储配置](/user-guide/deployments/configuration.md#存储选项)文档。 + +由于云存储在存储管理方面的简单性,强烈推荐使用云存储进行数据存储。 +使用云存储时,本地存储空间只需要大约 200GB 用于查询相关的缓存和 Write-Ahead Log (WAL)。 + +无论你选择云存储还是本地存储, +建议设置[保留策略](/user-guide/concepts/features-that-you-concern.md#我可以为不同的表或指标设置-ttl-或保留策略吗)以有效管理存储成本。 + +## 举例 + +假设你的数据库每秒处理约 200 个简单查询请求(QPS),每秒处理约 300k 数据点的写入请求,使用云存储存储数据。 + +在这种写入和查询速率下, +以下是你可能分配资源的示例: + +- CPU:8 核 +- 内存:32 GB +- 存储空间:200 GB + +这样的分配旨在优化性能, +确保数据写入和查询处理的平稳进行,而不会导致系统过载。 +然而,请记住这些只是建议, +实际需求可能会根据特定的工作负载特征和性能期望而有所不同。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/administration/disaster-recovery/back-up-&-restore-data.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/administration/disaster-recovery/back-up-&-restore-data.md new file mode 100644 index 000000000..e1ef42a00 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/administration/disaster-recovery/back-up-&-restore-data.md @@ -0,0 +1,158 @@ +--- +keywords: [备份, 恢复, 导出工具, 导入工具, 数据库备份, 数据恢复, 命令行工具, 使用场景, 最佳实践] +description: 介绍 GreptimeDB 的导出和导入工具,用于数据库备份和恢复,包括命令语法、选项、常见使用场景、最佳实践和故障排除等内容。 +--- + +# GreptimeDB 导出和导入工具 + +本指南描述了如何使用 GreptimeDB 的导出和导入工具进行数据库备份和恢复。 + +导出和导入工具提供了备份和恢复 GreptimeDB 数据库的功能。这些工具可以处理 schema(表结构等)和数据,支持完整或选择性的备份和恢复操作。 + +## 导出工具 + +### 命令语法 +```bash +greptime cli export [OPTIONS] +``` + +### 选项 +| 选项 | 是否必需 | 默认值 | 描述 | +|--------|----------|---------|-------------| +| --addr | 是 | - | 要连接的 GreptimeDB 数据库地址 | +| --output-dir | 是 | - | 存储导出数据的目录 | +| --database | 否 | 所有数据库 | 要导出的数据库名称 | +| --export-jobs, -j | 否 | 1 | 并行导出任务数量(多个数据库可以并行导出) | +| --max-retry | 否 | 3 | 每个任务的最大重试次数 | +| --target, -t | 否 | all | 导出目标(schema/data/all) | +| --start-time | 否 | - | 数据导出的开始时间范围 | +| --end-time | 否 | - | 数据导出的结束时间范围 | +| --auth-basic | 否 | - | 使用 `:` 格式 | +| --timeout | 否 | 0 | 对 DB 进行一次调用的超时时间,默认为 0 代表永不超时 (例如 `30s`, `10min 20s`) | + +### 导出目标 +- `schema`: 仅导出表结构(`SHOW CREATE TABLE`) +- `data`: 仅导出表数据(`COPY DATABASE TO`) +- `all`: 导出表结构和数据(默认) + +### 输出目录结构 +``` +/ +└── greptime/ + └── / + ├── create_database.sql + ├── create_tables.sql + ├── copy_from.sql + └── <数据文件> +``` + +## 导入工具 + +### 命令语法 +```bash +greptime cli import [OPTIONS] +``` + +### 选项 +| 选项 | 是否必需 | 默认值 | 描述 | +|--------|----------|---------|-------------| +| --addr | 是 | - | 要连接的 GreptimeDB 数据库地址 | +| --input-dir | 是 | - | 包含备份数据的目录 | +| --database | 否 | 所有数据库 | 要导入的数据库名称 | +| --import-jobs, -j | 否 | 1 | 并行导入任务数量(多个数据库可以并行导入) | +| --max-retry | 否 | 3 | 每个任务的最大重试次数 | +| --target, -t | 否 | all | 导入目标(schema/data/all) | +| --auth-basic | 否 | - | 使用 `:` 格式 | + +### 导入目标 +- `schema`: 仅导入表结构 +- `data`: 仅导入表数据 +- `all`: 导入表结构和数据(默认) + +## 常见使用场景 + +### 完整数据库备份 +```bash +# 导出所有数据库备份 +greptime cli export --addr localhost:4000 --output-dir /tmp/backup/greptimedb + +# 导入所有数据库 +greptime cli import --addr localhost:4000 --input-dir /tmp/backup/greptimedb +``` + +### 仅表结构操作 +```bash +# 仅导出表结构 +greptime cli export --addr localhost:4000 --output-dir /tmp/backup/schemas --target schema + +# 仅导入表结构 +greptime cli import --addr localhost:4000 --input-dir /tmp/backup/schemas --target schema +``` + +### 基于时间范围的备份 +```bash +# 导出特定时间范围内的数据 +greptime cli export --addr localhost:4000 \ + --output-dir /tmp/backup/timerange \ + --start-time "2024-01-01 00:00:00" \ + --end-time "2024-01-31 23:59:59" +``` + +### 指定数据库备份 +```bash +# 导出指定数据库 +greptime cli export --addr localhost:4000 --output-dir /tmp/backup/greptimedb --database '{my_database_name}' + +# 导入工具也同样适用 +greptime cli import --addr localhost:4000 --input-dir /tmp/backup/greptimedb --database '{my_database_name}' +``` + +## 最佳实践 + +1. **并行度配置** + - 根据可用系统资源调整 `--export-jobs`/`--import-jobs` + - 从较低的值开始,逐步增加 + - 在操作期间监控系统性能 + +2. **备份策略** + - 使用时间范围进行增量数据备份 + - 定期备份用于灾难恢复 + +3. **错误处理** + - 使用 `--max-retry` 处理临时异常 + - 保留日志以便故障排除 + +## 故障排除 + +### 常见问题 + +1. **连接错误** + - 验证服务器地址和端口 + - 检查网络连接 + - 确保身份验证凭据正确 + +2. **权限问题** + - 验证输出/输入目录的读写权限 + +3. **资源限制** + - 减少并行任务数 + - 确保足够的磁盘空间 + - 在操作期间监控系统资源 + +### 性能提示 + +1. **导出性能** + - 对大型数据集使用时间范围 + - 根据 CPU/内存调整并行任务数量 + - 考虑网络带宽限制 + +2. **导入性能** + - 注意监控数据库资源 + +1. **导出性能** + - 对大型数据集使用时间范围 + - 根据 CPU/内存调整并行任务 + - 考虑网络带宽限制 + +2. **导入性能** + - 监控数据库资源 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/administration/disaster-recovery/dr-solution-based-on-cross-region-deployment-in-single-cluster.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/administration/disaster-recovery/dr-solution-based-on-cross-region-deployment-in-single-cluster.md new file mode 100644 index 000000000..3f332440f --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/administration/disaster-recovery/dr-solution-based-on-cross-region-deployment-in-single-cluster.md @@ -0,0 +1,125 @@ +--- +keywords: [跨区域部署, 单集群, 灾难恢复, DR 解决方案, 数据中心, 高可用性, 网络延迟, 元数据, 数据分区] +description: 介绍 GreptimeDB 基于单集群跨区域部署的灾难恢复(DR)解决方案,包括不同区域和数据中心的部署架构及其比较。 +--- + +# 基于单集群跨区域部署的 DR 解决方案 + +## GreptimeDB DR 的工作原理 +GreptimeDB 非常适合跨区域灾难恢复。GreptimeDB 提供了量身定制的解决方案,以满足不同区域特征和业务需求的多样化要求。 + +GreptimeDB 资源管理涉及 Availability Zones(AZ)的概念。一个 AZ 是一个逻辑上的灾难恢复单元。 +它可以是数据中心(DC),也可以是 DC 的一个分区,这取决于你具体的 DC 条件和部署设计。 + +在跨区域灾难恢复解决方案中,一个 GreptimeDB 区域是一个城市。当两个 DC 在同一区域且其中一个 DC 不可用时,另一个 DC 可以接管不可用 DC 的服务。这是一种本地化策略。 + +在了解每个 DR 解决方案的细节之前,有必要先了解以下知识: +1. Remote wal 组件的 DR 解决方案也非常重要。本质上,它构成了整个 DR 解决方案的基础。因此,对于每个 GreptimeDB 的 DR 解决方案,我们将在图中展示 remote wal 组件。目前,GreptimeDB 默认使用基于 Kafka 实现的 remote wal 组件,将来会提供其他实现;然而,在部署上不会有显著差异。 +2. GreptimeDB 表:每张表可以根据一定范围划分为多个分区,每个分区可能分布在不同的数据节点上。在写入或查询时,会根据相应的路由规则调用到指定的数据节点。一张表的分区可能如下所示: + +``` +Table name: T1 +Table partition count: 4 + T1-1 + T1-2 + T1-3 + T1-4 + +Table name: T2 +Table partition count: 3 + T2-1 + T2-2 + T2-3 +``` + + +### 元数据跨两个区域,数据在同一区域 + +![DR-across-2dc-1region](/DR-across-2dc-1region.png) + +在此解决方案中,数据位于一个区域(2 个 DC),而元数据跨越两个区域。 + +DC1 和 DC2 一起用于处理读写服务,而位于第二区域的 DC3 是用来满足多数派协议的副本。这种架构也被称为 “2-2-1” 解决方案。 + +在极端情况下,DC1 和 DC2 都必须能够处理所有请求,因此请确保分配足够的资源。 + +网络延迟: +- 同一区域内延迟为 2ms +- 两个区域间延迟为 30ms + +支持高可用性级别: +- 单个 AZ 不可用时性能相同 +- 单个 DC 不可用时性能几乎相同 + +如果您想要一个区域级别的灾难恢复解决方案,可以更进一步,在 DC3 上提供读写服务。因此,下一个解决方案是: + +### 数据跨两个区域 + +![DR-across-3dc-2region](/DR-across-3dc-2region.png) + +在此解决方案中,数据跨越两个区域。 + +每个数据中心必须能够在极端情况下处理所有请求,因此请确保分配足够的资源。 + +网络延迟: +- 同一区域内延迟为 2 毫秒 +- 两个区域间延迟为 30 毫秒 + +支持高可用性级别: +- 单个可用区不可用时性能不变 +- 单个数据中心不可用时性能下降 + +如果无法容忍单个数据中心故障导致的性能下降,请考虑升级到五个数据中心和三个区域的解决方案。 + +### 元数据跨三个区域,数据跨两个区域 + +![DR-across-5dc-2region](/DR-across-5dc-2region.png) + +在此解决方案中,数据跨越两个区域,而元数据跨越三个区域。 + +Region1 和 Region2 一起用于处理读写服务,而 Region3 是一个副本,用于满足多数派协议。这种架构也被称为 “2-2-1” 解决方案。 + +两个相邻的区域中的每一个都必须能够在极端情况下处理所有请求,因此请确保分配足够的资源。 + +网络延迟: +- 同一区域内延迟为 2ms +- 两个相邻区域之间延迟为 7ms +- 两个远距离区域之间延迟为 30ms + +支持高可用性级别: +- 单一 AZ 不可用时性能不变 +- 单一 DC 不可用时性能不变 +- 单一区域(城市)不可用时性能略有下降 + +您可以更进一步,在三个区域上提供读写服务。因此,下一个解决方案是: +(此解决方案可能具有更高的延迟,如果无法接受,则不推荐。) + +## 数据跨三个区域 + +![DR-across-5dc-3region](/DR-across-5dc-3region.png) + +在此解决方案中,数据跨越三个区域。 + +如果一个区域发生故障,其他两个区域必须能够处理所有请求,因此请确保分配足够的资源。 + +网络延迟: +- 同一区域内延迟为 2 毫秒 +- 相邻两个区域之间的延迟为 7 毫秒 +- 两个远距离区域之间的延迟为 30 毫秒 + +支持高可用性级别: +- 单个 AZ 不可用时性能不变 +- 单个 DC 不可用时性能不变 +- 单个区域(城市)不可用时性能下降 + +## 解决方案比较 +上述解决方案的目标是在中大型场景中满足高可用性和可靠性的要求。然而,在具体实施过程中,每种解决方案的成本和效果可能会有所不同。下表对每种解决方案进行了比较,以帮助你根据具体场景、需求和成本进行最终选择。 + +以下是内容格式化为表格: + +| 解决方案 | 延迟 | 高可用性 | +| --- | --- | --- | +| 元数据跨两个区域,数据在同一区域 | - 同一区域内延迟 2 毫秒
- 两个区域间延迟 30 毫秒 | - 单个 AZ 不可用时性能不变
- 单个 DC 不可用时性能几乎不变 | +| 数据跨两个区域 | - 同一区域内延迟 2 毫秒
- 两个区域间延迟 30 毫秒 | - 单个 AZ 不可用时性能不变
- 单个 DC 不可用时性能下降 | +| 元数据跨三个区域,数据跨两个区域 | - 同一区域内延迟 2 毫秒
- 相邻两个区域间延迟 7 毫秒
- 两个远距离的区域间延迟 30 毫秒 | - 单个 AZ 不可用时性能不变
- 单个 DC 不可用时性能不变
- 单一区域(城市)不可用时,性能略有下降 | +| 数据跨三个区域 | - 同一区域内延迟 2 毫秒
- 相邻两个区域间延迟 7 毫秒
- 两个远距离的区域间延迟 30 毫秒 | - 单个 AZ 不可用时性能不变
- 单个 DC 不可用时性能不变
- 单一区域(城市)不可用时, 性能下降 | diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/administration/disaster-recovery/dr-solution-for-standalone.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/administration/disaster-recovery/dr-solution-for-standalone.md new file mode 100644 index 000000000..0bf03d6aa --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/administration/disaster-recovery/dr-solution-for-standalone.md @@ -0,0 +1 @@ +# GreptimeDB Standalone 的 DR 方案 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/administration/disaster-recovery/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/administration/disaster-recovery/overview.md new file mode 100644 index 000000000..1b3bba9f2 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/administration/disaster-recovery/overview.md @@ -0,0 +1,147 @@ +--- +keywords: [灾难恢复, DR 解决方案, 备份与恢复, RTO, RPO, 组件架构, 双活互备, 跨区域部署, 数据恢复] +description: 介绍 GreptimeDB 的灾难恢复(DR)解决方案,包括基本概念、组件架构、不同的 DR 解决方案及其比较。 +--- + +# 概述 + +作为分布式数据库,GreptimeDB 提供了不同的灾难恢复(DR)解决方案。 + +本文档包括以下内容: +* DR 中的基本概念 +* GreptimeDB 中备份与恢复(BR)的部署架构。 +* GreptimeDB 的 DR 解决方案。 +* DR 解决方案的比较。 + +## 基本概念 + +* **恢复时间目标(RTO)**:指灾难发生后业务流程可以停止的最长时间,而不会对业务产生负面影响。 +* **恢复点目标(RPO)**:指自上一个数据恢复点以来可接受的最大时间量,决定了上一个恢复点和服务中断之间可接受的数据丢失量。 + +下图说明了这两个概念: + +![RTO-RPO-explain](/RTO-RPO-explain.png) + +* **预写式日志(WAL)**:持久记录每个数据修改,以确保数据的完整性和一致性。 + +GreptimeDB 存储引擎是一个典型的 [LSM 树](https://en.wikipedia.org/wiki/Log-structured_merge-tree): + +![LSM-tree-explain](/LSM-tree-explain.png) + +写入的数据首先持久化到 WAL,然后应用到内存中的 Memtable。 +在特定条件下(例如超过内存阈值时), +Memtable 将被刷新并持久化为 SSTable。 +因此,WAL 和 SSTable 的备份恢复是 GreptimeDB 灾难恢复的关键。 + +* **Region**:表的连续段,也可以被视为某些关系数据库中的分区。请阅读[表分片](/contributor-guide/frontend/table-sharding.md#region)以获取更多详细信息。 + +## 组件架构 + +### GreptimeDB + +在深入了解具体的解决方案之前,让我们从灾难恢复的角度看一下 GreptimeDB 组件的架构: + +![Component-architecture](/Component-architecture.png) + +GreptimeDB 基于存储计算分离的云原生架构设计: + +* **Frontend**:数据插入和查询的服务层,将请求转发到 Datanode 并处理和合并 Datanode 的响应。 +* **Datanode**:GreptimeDB 的存储层,是一个 LSM 存储引擎。Region 是在 Datanode 中存储和调度数据的基本单元。Region 是一个表分区,是一组数据行的集合。Region 中的数据保存在对象存储中(例如 AWS S3)。未刷新的 Memtable 数据被写入 WAL,并可以在灾难发生时恢复。 +* **WAL**:持久化内存中未刷新的 Memtable 数据。当 Memtable 被刷新到 SSTable 文件时,WAL 将被截断。它可以是基于本地磁盘的(本地 WAL)或基于 Kafka 集群的(远程 WAL)。 +* **对象存储**:持久化 SSTable 数据和索引。 + +GreptimeDB 将数据存储在对象存储(如 [AWS S3](https://docs.aws.amazon.com/AmazonS3/latest/userguide/DataDurability.html))或兼容的服务中,这些服务在年度范围内提供了 99.999999999% 的持久性和 99.99% 的可用性。像 S3 这样的服务提供了[单区域或跨区域的复制](https://docs.aws.amazon.com/AmazonS3/latest/userguide/replication.html),天然具备灾难恢复能力。 + +同时,WAL 组件是可插拔的,例如使用 Kafka 作为 WAL 服务以提供成熟的[灾难恢复解决方案](https://www.confluent.io/blog/disaster-recovery-multi-datacenter-apache-kafka-deployments/)。 + +### 备份与恢复 + +![BR-explain](/BR-explain.png) + +备份与恢复(BR)工具可以在特定时间对数据库或表进行完整快照备份,并支持增量备份。 +当集群遇到灾难时,你可以使用备份数据恢复集群。 +一般来说,BR 是灾难恢复的最后手段。 + +## 解决方案介绍 + +### GreptimeDB Standalone 的 DR 方案 + +如果 GreptimeDB Standalone 在本地磁盘上运行 WAL 和数据,那么: + +* RPO:取决于备份频率。 +* RTO:在 Standalone 没有意义,主要取决于要恢复的数据大小、故障响应时间和操作基础设施。 + +选择将 GreptimeDB Standalone 部署到具有备份和恢复解决方案的 IaaS 平台中是一个很好的开始,例如亚马逊 EC2(结合 EBS 卷)提供了全面的[备份和恢复解决方案](https://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/backup-recovery/backup-recovery-ec2-ebs.html)。 + +但是如果使用远程 WAL 和对象存储运行 Standalone,有一个更好的 DR 解决方案: + +![DR-Standalone](/DR-Standalone.png) + +将 WAL 写入 Kafka 集群,并将数据存储在对象存储中,因此数据库本身是无状态的。 +在影响独立数据库的灾难事件发生时,你可以使用远程 WAL 和对象存储来恢复它。 +此方案能实现 RPO=0 和分钟级 RTO。 + +有关此解决方案的更多信息,请参阅[独立模式的 DR 解决方案](./dr-solution-for-standalone.md)。 + +### 基于双活互备的 DR 解决方案 + +![Active-active failover](/active-active-failover.png) + +在某些边缘或中小型场景中,或者如果你没有资源部署远程 WAL 或对象存储,双活互备相对于 Standalone 的灾难恢复提供了更好的解决方案。 +通过在两个独立节点之间同步复制请求,确保了高可用性。 +即使使用基于本地磁盘的 WAL 和数据存储,任何单个节点的故障也不会导致数据丢失或服务可用性降低。 + +在不同区域部署节点也可以满足区域级灾难恢复要求,但可扩展性有限。 + +:::tip 注意 +**双活互备功能仅在 GreptimeDB 企业版中提供。** +::: + +有关此解决方案的更多信息,请参阅[基于双活-备份的 DR 解决方案](/enterprise/administration/disaster-recovery/dr-solution-based-on-active-active-failover.md)。 + +### 基于单集群跨区域部署的 DR 解决方案 + +![Cross-region-single-cluster](/Cross-region-single-cluster.png) + +对于需要零 RPO 的中大型场景,强烈推荐此解决方案。 +在此部署架构中,整个集群跨越三个 Region,每个 Region 都能处理读写请求。 +两者都必须启用跨 Region DR 并使用远程 WAL 和对象存储实现数据复制。 +如果 Region 1 因灾难而完全不可用,其中的表 Region 将在其他 Region 中打开和恢复。 +Region 3 作为副本遵循 Metasrv 的多种协议。 + +此解决方案提供 Region 级别的容错、可扩展的写入能力、零 RPO 和分钟级或更低的 RTO。 +有关此解决方案的更多信息,请参阅[基于单集群跨区域部署的 DR 解决方案](./dr-solution-based-on-cross-region-deployment-in-single-cluster.md)。 + +### 基于备份恢复的 DR 解决方案 + +![/BR-DR](/BR-DR.png) + +在此架构中,GreptimeDB Cluster 1 部署在 Region 1。 +BR 进程持续定期将数据从 Cluster 1 备份到 Region 2。 +如果 Region 1 遭遇灾难导致 Cluster 1 无法恢复, +你可以使用备份数据恢复 Region 2 中的新集群(Cluster 2)以恢复服务。 + +基于 BR 的 DR 解决方案提供的 RPO 取决于备份频率,RTO 随要恢复的数据大小而变化。 + +阅读[备份与恢复数据](./back-up-&-restore-data.md)获取详细信息,我们计划为此解决方案提供一种内部 BR 工具。 + +### 解决方案比较 + +通过比较这些 DR 解决方案,你可以根据其特定场景、需求和成本选择最终的选项。 + + +| DR 解决方案 | 容错目标 | RPO | RTO | TCO | 场景 | 远程 WAL 和对象存储 | 备注 | +| ------------- | ------------------------- | ----- | ----- | ----- | ---------------- | --------- | --------| +| 独立模式的 DR 解决方案| 单区域 | 备份间隔 | 分钟或小时级 | 低 | 小型场景中对可用性和可靠性要求较低 | 可选 | | +| 基于双活-备份的 DR 解决方案| 跨区域 | 0 | 分钟级 | 低 | 中小型场景中对可用性和可靠性要求较高 | 可选 | 商业功能 | +| 基于单集群跨区域部署的 DR 解决方案| 多区域 | 0 | 分钟级 | 高 | 中大型场景中对可用性和可靠性要求较高 | 必需 | | +| 基于 BR 的 DR 解决方案 | 单区域 | 备份间隔 | 分钟或小时级 | 低 | 可接受的可用性和可靠性要求 | 可选 | | + + +## 参考资料 + +* [备份与恢复数据](./back-up-&-restore-data.md) +* [GreptimeDB Standalone 的 DR 解决方案](./dr-solution-for-standalone.md) +* [基于双活-备份的 DR 解决方案](/enterprise/administration/disaster-recovery/dr-solution-based-on-active-active-failover.md) +* [基于单集群跨区域部署的 DR 解决方案](./dr-solution-based-on-cross-region-deployment-in-single-cluster.md) +* [S3 对象副本概述](https://docs.aws.amazon.com/AmazonS3/latest/userguide/replication.html) diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/user-guide/table-management.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/administration/manage-data/basic-table-operations.md similarity index 55% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7/user-guide/table-management.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/administration/manage-data/basic-table-operations.md index 881cf9ac3..891fc5520 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/user-guide/table-management.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/administration/manage-data/basic-table-operations.md @@ -1,6 +1,11 @@ -# 管理表 +--- +keywords: [表操作, 创建表, 修改表, 删除表, 描述表] +description: 介绍 GreptimeDB 中表的基本操作,包括创建数据库和表、描述表、显示表定义和索引、列出现有表、修改表和删除表等内容。 +--- -在阅读本文档之前请先阅读 [数据模型](./concepts/data-model.md). +# 表的基本操作 + +在阅读本文档之前请先阅读 [数据模型](/user-guide/concepts/data-model.md). GreptimeDB 通过 SQL 提供了表管理的功能,下面通过 [MySQL Command-Line Client](https://dev.mysql.com/doc/refman/8.0/en/mysql.html) 来演示它。 @@ -18,6 +23,12 @@ CREATE DATABASE test; Query OK, 1 row affected (0.05 sec) ``` +创建一个具有 7 天 `TTL`(数据存活时间)的数据库,也就是该数据库中的所有表如果没有单独设置 TTL 选项,都将继承此选项值。 + +```sql +CREATE DATABASE test WITH (ttl='7d'); +``` + 列出所有现有的数据库。 ```sql @@ -64,7 +75,7 @@ USE public; ## 创建表 :::tip NOTE -注意:GreptimeDB 提供了一种 schemaless 方法来写入数据,不需要使用额外的协议手动创建表。参见 [自动生成表结构](/user-guide/write-data/overview.md#自动生成表结构)\*\*。 +注意:GreptimeDB 提供了一种 schemaless 方法来写入数据,不需要使用额外的协议手动创建表。参见 [自动生成表结构](/user-guide/ingest-data/overview.md#自动生成表结构)\*\*。 ::: 如果您有特殊需要,仍然可以通过 SQL 手动创建表。假设我们想要创建一个名为 `monitor` 的表,其数据模型如下: @@ -81,16 +92,29 @@ CREATE TABLE monitor ( ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP() TIME INDEX, cpu FLOAT64 DEFAULT 0, memory FLOAT64, - PRIMARY KEY(host)) ENGINE=mito WITH(regions=1); + PRIMARY KEY(host)); ``` ```sql Query OK, 0 row affected (0.03 sec) ``` +创建一个具有 7 天 `TTL`(数据存活时间)的表: + +```sql +CREATE TABLE monitor ( + host STRING, + ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP() TIME INDEX, + cpu FLOAT64 DEFAULT 0, + memory FLOAT64, + PRIMARY KEY(host) +) WITH (ttl='7d'); +``` + + :::warning NOTE -GreptimeDB 目前不支持在创建表后更改已有列的数据模型。 -因此,在创建表之前,仔细设计数据模型非常重要。 +GreptimeDB 目前不支持在创建表后更改 TIME INDEX 约束, +因此,在创建表之前,仔细选择适当的 TIME INDEX 列。 ::: ### `CREATE TABLE` 语法 @@ -98,14 +122,15 @@ GreptimeDB 目前不支持在创建表后更改已有列的数据模型。 - 时间戳列:GreptimeDB 是一个时序数据库系统,在创建表时,必须用 `TIME INDEX` 关键字明确指定时间序列的列。 时间序列的列的数据类型必须是 `TIMESTAMP`。 - 主键:`Primary key`指定的主键列类似于其他时序系统中的 Tag,比如 [InfluxDB][1]。 主键和时间戳列用于唯一地定义一条时间线,这类似于其他时间序列系统中的时间线的概念,如 [InfluxDB][2]。 -- 表选项:当创建一个表时,可以指定一组表选项,点击[这里](../reference/sql/create.md#table-options)了解更多细节。 +- 表选项:当创建一个表时,可以指定一组表选项,点击[这里](/reference/sql/create.md#table-options)了解更多细节。 -### 表名的限制条件 +### 表名约束 GreptimeDB 支持在表名中使用有限的特殊字符,但必须遵守以下约束: - 有效的 GreptimeDB 表名必须以字母(小写或大写)或 `-` / `_` / `:` 开头。 -- 表名的其余部分可以是字母数字或以下特殊字符:`-` / `_` / `:`。 +- 表名的其余部分可以是字母数字或以下特殊字符:`-` / `_` / `:` / `@` / `#`。 - 任何包含特殊字符的表名都必须用反引号括起来。 +- 任何包含大写字母的表名都必须用反引号括起来。 以下是有效和无效表名的例子: @@ -124,6 +149,15 @@ create table -a (ts timestamp time index); -- ✅ Ok create table `-a` (ts timestamp time index); + +-- ✅ Ok +create table `a@b` (ts timestamp time index); + +-- 🚫 Invalid table name +create table memory_HugePages (ts timestamp time index); + +-- ✅ Ok +create table `memory_HugePages` (ts timestamp time index); ``` [1]: https://docs.influxdata.com/influxdb/v1.8/concepts/glossary/#tag-key @@ -151,6 +185,49 @@ DESC TABLE monitor; Semantic Type 列描述了表的数据模型。`host` 是 `Tag` 列,`ts` 是 `Timestamp` 列,`cpu` 和 `memory` 是 `Field` 列。 +## 显示表定义和索引 + +使用 `SHOW CREATE TABLE table_name` 来获取创建表时的语句: + +```sql +SHOW CREATE TABLE monitor; +``` + +``` ++---------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| Table | Create Table | ++---------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| monitor | CREATE TABLE IF NOT EXISTS `monitor` ( + `host` STRING NULL, + `ts` TIMESTAMP(3) NOT NULL DEFAULT current_timestamp(), + `cpu` DOUBLE NULL DEFAULT 0, + `memory` DOUBLE NULL, + TIME INDEX (`ts`), + PRIMARY KEY (`host`) +) + +ENGINE=mito + | ++---------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +``` + +列出表中的所有索引: + +```sql +SHOW INDEXES FROM monitor; +``` + +```sql ++---------+------------+------------+--------------+-------------+-----------+-------------+----------+--------+------+----------------------------+---------+---------------+---------+------------+ +| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment | Visible | Expression | ++---------+------------+------------+--------------+-------------+-----------+-------------+----------+--------+------+----------------------------+---------+---------------+---------+------------+ +| monitor | 1 | PRIMARY | 1 | host | A | NULL | NULL | NULL | YES | greptime-inverted-index-v1 | | | YES | NULL | +| monitor | 1 | TIME INDEX | 1 | ts | A | NULL | NULL | NULL | NO | greptime-inverted-index-v1 | | | YES | NULL | ++---------+------------+------------+--------------+-------------+-----------+-------------+----------+--------+------+----------------------------+---------+---------------+---------+------------+ +``` + +有关 `SHOW` 语句的更多信息,请阅读 [SHOW 参考](/reference/sql/show.md#show)。 + ## 列出现有的表 可以使用 `show tables` 语句来列出现有的表 @@ -221,10 +298,14 @@ ALTER TABLE monitor DROP COLUMN label; Query OK, 0 rows affected (0.03 sec) ``` -注意:目前只允许添加/删除列,将很快支持改变列的定义。 +`ALTER TABLE` 语句还支持添加、删除、重命名列以及修改列的数据类型等更改。有关更多信息,请参阅[ALTER 参考指南](/reference/sql/alter.md)。 ## 删除表 +:::danger 危险操作 +表删除后不可撤销!请谨慎操作! +::: + `DROP TABLE [db.]table` 用于删除 `db` 或当前正在使用的数据库中的表。 删除当前数据库中的表 `test`: @@ -237,6 +318,21 @@ DROP TABLE monitor; Query OK, 1 row affected (0.01 sec) ``` +## 删除数据库 + +:::danger 危险操作 +数据库删除后不可撤销!请谨慎操作! +::: + +可以使用 `DROP DATABASE` 删除数据库。 +例如,删除 `test` 数据库: + +```sql +DROP DATABASE test; +``` + +请前往 [DROP](/reference/sql/drop.md#drop-database) 文档了解更多内容。 + ## HTTP API 使用以下代码,通过 POST 方法创建一个表: @@ -245,7 +341,7 @@ Query OK, 1 row affected (0.01 sec) curl -X POST \ -H 'authorization: Basic {{authorization if exists}}' \ -H 'Content-Type: application/x-www-form-urlencoded' \ - -d 'sql=CREATE TABLE monitor (host STRING, ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP(), cpu FLOAT64 DEFAULT 0, memory FLOAT64, TIME INDEX (ts), PRIMARY KEY(host)) ENGINE=mito WITH(regions=1)' \ + -d 'sql=CREATE TABLE monitor (host STRING, ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP(), cpu FLOAT64 DEFAULT 0, memory FLOAT64, TIME INDEX (ts), PRIMARY KEY(host))' \ http://localhost:4000/v1/sql?db=public ``` @@ -253,11 +349,11 @@ http://localhost:4000/v1/sql?db=public { "code": 0, "output": [{ "affectedrows": 1 }], "execution_time_ms": 10 } ``` -关于 SQL HTTP 请求的更多信息,请参考 [API 文档](/reference/sql/http-api.md)。 +关于 SQL HTTP 请求的更多信息,请参考 [API 文档](/user-guide/protocols/http.md#post-sql-语句)。 ## 时区 SQL 客户端会话中指定的时区将影响创建或更改表时的默认时间戳值。 如果将时间戳列的默认值设置为不带时区的字符串,则该默认值会被自动添加客户端的时区信息。 -有关客户端时区的影响,请参考 [写入数据](./write-data/sql.md#时区) 文档中的时区部分。 +有关客户端时区的影响,请参考 [写入数据](/user-guide/ingest-data/for-iot/sql.md#时区) 文档中的时区部分。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/administration/manage-data/compaction.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/administration/manage-data/compaction.md new file mode 100644 index 000000000..3d4ed1468 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/administration/manage-data/compaction.md @@ -0,0 +1,148 @@ +--- +keywords: [压缩策略, 时间窗口压缩, 严格窗口压缩, SST 文件, 手动压缩] +description: 介绍 GreptimeDB 中的压缩策略,包括时间窗口压缩策略(TWCS)和严格窗口压缩策略(SWCS),以及它们的概念、参数和使用示例。 +--- + +# Compaction + +对于基于 LSM 树的数据库,压缩是极其关键的。它将重叠的碎片化 SST 文件合并成一个有序的文件,丢弃已删除的数据,同时显著提高查询性能。 + +从 v0.9.1 版本开始,GreptimeDB 提供了控制 SST 文件如何压缩的策略:时间窗口压缩策略(TWCS)和严格窗口压缩策略(SWCS)。 + +## 概念 + +让我们从 GreptimeDB 中压缩的核心概念开始介绍。 + +### SST 文件 + +当内存表刷新到持久存储(如磁盘和对象存储)时,会生成排序的 SST 文件。 + +在 GreptimeDB 中,SST 文件中的数据行按[tag 列](/user-guide/concepts/data-model.md)和时间戳组织,如下所示。每个 SST 文件覆盖特定的时间范围。当查询指定一个时间范围时,GreptimeDB 只检索可能包含该范围内数据的相关 SST 文件,而不是加载所有已持久化的文件。 + +![SST layout](/compaction-sst-file-layout.jpg) + +通常,在实时写入工作负载中,SST 文件的时间范围不会重叠。然而,由于数据删除和乱序写入等因素,SST 文件可能会有重叠的时间范围,这会影响查询性能。 + +### 时间窗口 + +时间序列工作负载呈现出显著的“窗口”特征,即最近插入的行更有可能被读取。因此,GreptimeDB 将时间轴逻辑上划分为不同的时间窗口,我们更关注压缩那些落在同一时间窗口内的 SST 文件。 + +特定表的时间窗口参数通常是从最新 flush 到存储的 SST 文件推断出来的,或者如果选择了 TWCS,您可以在建表时手动指定时间窗口。 + +GreptimeDB 预设了一组窗口大小,它们是: +- 1 小时 +- 2 小时 +- 12 小时 +- 1 天 +- 1 周 +- 1 年 +- 10 年 + +如果未指定时间窗口大小,GreptimeDB 将在第一次压缩时推断窗口,通过从上述集合中选择**能够覆盖所有要压缩文件的整个时间跨度的**,**最小的**时间窗口作为时间窗口大小。 + +例如,在第一次压缩期间,所有输入 SST 文件的时间跨度为 4 小时,那么 GreptimeDB 将选择 12 小时作为该表的时间窗口,并将此参数持久化以便后续的压缩中使用。 + +GreptimeDB 将包含最近插入时间戳的窗口视为**活跃窗口(active window)**,而将之前的那些窗口视为**非活跃窗口(inactive window)**。 + +### 有序组 +有序组(sorted runs)是一个包含已排序且时间范围不重叠的 SST 文件的集合。 + +例如,一个表包含 5 个 SST,时间范围如下(全部包括在内):`[0, 10]`, `[12, 23]`, `[22, 25]`,`[24, 30]`,`[26,33]`,我们可以找到 2 个有序组: + +![num-of-sorted-runs](/compaction-num-sorted-runs.jpg) + + +有序组的数量往往能够反映 SST 文件的有序性。更多的有序组通常会导致查询性能变差,因为特定时间范围的查询往往会命中多个重叠的文件。压缩的主要目标是减少有序组的数量。 + +### 层级 + +基于 LSM 树的数据库常常有多个层级,数据的键(key)会逐层进行合并。GreptimeDB 只有两个层级,分别是 0(未压缩)和 1(已压缩)。 + +## 压缩策略 + +GreptimeDB 提供了上述两种压缩策略,但在创建表时只能选择时间窗口压缩策略(TWCS)。严格窗口(SWCS)仅在执行手动压缩时可用。 + +## 时间窗口压缩策略(TWCS) + +TWCS 主要旨在减少压缩过程中的读 / 写放大。 + +它将要压缩的文件分配到不同的时间窗口。对于每个窗口,TWCS 会识别有序组。如有序组的数量超过了允许的最大值,TWCS 会找到一个解决方案,在考虑合并惩罚的同时将其减少到阈值以下。如果有序组的数量没有超过阈值,TWCS 会检查是否存在过多的文件碎片,并在必要时合并这些碎片文件,因为 SST 文件数量也会影响查询性能。 + +对于窗口分配,SST 文件可能跨越多个时间窗口。为了确保不受陈旧数据影响,TWCS 根据 SST 的最大时间戳来进行分配。在时间序列工作负载中,无序写入很少发生,即使发生了,最近数据的查询性能也比陈旧数据更为重要。 + +TWCS 提供了 5 个参数供调整: +- `max_active_window_runs`: 活跃窗口中最大允许存在的有序组数量(默认为 4) +- `max_active_window_files`: 活跃窗口中最大允许存在的文件数量(默认为 4) +- `max_inactive_window_runs`: 非活跃窗口中最大允许存在的有序组数量(默认为 1) +- `max_inactive_window_files`: 非活跃窗口中最大允许存在的文件数量(默认为 1) +- `max_output_file_size`: compaction 产生文件的最大大小(默认无限制) + +您可以为活跃窗口和非活跃窗口设置不同的阈值。这很重要,因为乱序写入通常发生在活跃窗口中。通过允许更多重叠文件存在于活跃窗口,TWCS 在数据摄取过程中减少了写放大,并在活跃窗口变为非活跃时合并所有这些文件。 + +以下图表显示了当最大活跃窗口允许的有序组数量为 1 时,活跃窗口中的文件如何被压缩: +- 在 A 中,有两个 SST 文件`[0, 3]`和`[5, 6, 9]`,但由于这两个文件的时间范围不重叠,因此只有一个有序组。 +- 在 B 中,一个新的 SST 文件`[1, 4]`被刷新,因此形成了两个有序组。然后将 `[0, 3]` 和 `[1, 4]` 合并为 `[0, 1, 3, 4]`. +- 在 C 中,一个新的 SST 文件 ` [9, 10 ] ` 被刷新,并且它将与 `[5, 6, 10 ] ` 合并以创建 `[5, 6, 9, 10]`. +- D 是最终状态,两个压缩后的文件中形成一个有序组。 + +![compaction-twcs-active.jpg](/compaction-twcs-active.jpg) + +### 指定 TWCS 参数 +用户可以在创建表时指定前述的 TWCS 参数,例如: + +```sql +CREATE TABLE monitor ( + host STRING, + ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP() TIME INDEX, + cpu FLOAT64 DEFAULT 0, + memory FLOAT64, + PRIMARY KEY(host)) +WITH ( + 'compaction.type'='twcs', + 'compaction.twcs.max_active_window_runs'='4', + 'compaction.twcs.max_active_window_files'='8', + 'compaction.twcs.max_inactive_window_runs'='1', + 'compaction.twcs.max_inactive_window_files'='2', + 'compaction.twcs.max_output_file_size'='500MB' + ); +``` + +## 严格窗口压缩策略(SWCS)和手动压缩 + +与 TWCS 根据 SST 文件的最大时间戳为每个窗口分配一个 SST 文件不同的是,严格窗口策略(SWCS)将 SST 文件分配给**所有与此文件的时间范围重叠**的窗口,正如其名称所示。因此,一个 SST 文件可能会包含在多个压缩输出中。由于其在压缩期间的高读取放大率,SWCS 并不是默认的压缩策略。然而,当用户需要手动触发压缩以重新组织 SST 文件布局时,它是有用的,特别是当单个 SST 文件跨越较大的时间范围而显著减慢查询速度时。GreptimeDB 提供了一个简单的 SQL 函数来触发手动压缩: + +```sql +ADMIN COMPACT_TABLE( + , + , + [] +); +``` + +`` 参数可以是 `twcs` 或 `swcs`(大小写不敏感),分别指定时间窗口压缩策略和严格窗口压缩策略。 +对于 `swcs` 策略, `` 指定用于拆分 SST 文件的窗口大小(以秒为单位)。例如: + +```sql +ADMIN COMPACT_TABLE( + "monitor", + "swcs", + "3600" +); + ++--------------------------------------------------------------------+ +| ADMIN compact_table(Utf8("monitor"),Utf8("swcs"),Utf8("3600")) | ++--------------------------------------------------------------------+ +| 0 | ++--------------------------------------------------------------------+ +1 row in set (0.01 sec) +``` + +执行此语句时,GreptimeDB 会将每个 SST 文件按 1 小时(3600 秒)的时间跨度拆分成多个分块,并将这些分块合并为一个输出文件,确保没有重叠的文件。 + +下图展示了一次 SWCS 压缩的过程: + +在图 A 中,有 3 个重叠的 SST 文件,分别是 `[0, 3]`(也就是包含 0、1、2、3 的时间戳)、`[3, 8]` 和 `[8, 10]`。 +严格窗口压缩策略会将覆盖了窗口 0、4、8 的文件 `[3, 8]` 分别分配给 3 个窗口,从而分别和 `[0, 3]` 以及 `[8, 10]` 合并。 +图 B 给出了最终的压缩结果,分别有 3 个文件: `[0, 3]`、`[4, 7]` 和 `[8, 10]`,它们彼此互相不重叠。 + +![compaction-strict-window.jpg](/compaction-strict-window.jpg) diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/administration/manage-data/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/administration/manage-data/overview.md new file mode 100644 index 000000000..f47d5b099 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/administration/manage-data/overview.md @@ -0,0 +1,15 @@ +--- +keywords: [数据管理, 存储位置, 表操作, 数据更新, TTL 策略] +description: 提供 GreptimeDB 数据管理的概述,包括存储位置说明、表的基本操作、更新或删除数据、TTL 策略、表分片、Region 迁移、Region Failover 和 Compaction 等内容。 +--- + +# 概述 + +* [存储位置说明](/user-guide/concepts/storage-location.md) +* [表的基本操作](basic-table-operations.md): 如何创建、修改和删除表 +* [更新或删除数据](/user-guide/manage-data/overview.md) +* [通过设置 TTL 过期数据](/user-guide/manage-data/overview.md#使用-ttl-策略保留数据) +* [表分片](table-sharding.md): 按 Region 对表进行分区 +* [Region Migration](region-migration.md): 为负载均衡迁移 Region +* [Region Failover](/user-guide/administration/manage-data/region-failover.md) +* [Compaction](compaction.md) diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/administration/manage-data/region-failover.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/administration/manage-data/region-failover.md new file mode 100644 index 000000000..0df187321 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/administration/manage-data/region-failover.md @@ -0,0 +1,86 @@ +--- +keywords: [Region Failover, 故障恢复, 恢复时间, 共享存储, Kafka WAL] +description: 介绍 Region Failover 功能及其在 GreptimeDB 中的应用,包括开启 Region Failover、恢复时间和改进恢复时间的建议等内容。 +--- + +# Region Failover + +Region Failover 提供了在不丢失数据的情况下从 Region 故障中恢复的能力。这是通过 [Region 迁移](/user-guide/administration/manage-data/region-migration.md) 实现的。 + +## 开启 Region Failover + + +该功能仅在 GreptimeDB 集群模式下可用,并且需要满足以下条件 + +- 使用 Kafka WAL +- 使用[共享存储](/user-guide/deployments/configuration.md#storage-options) (例如:AWS S3) + + +### 通过配置文件 + +在 [metasrv](/user-guide/deployments/configuration.md#metasrv-only-configuration) 配置文件中设置 `enable_region_failover=true`. + +### 通过 GreptimeDB Operator + +通过设置 `meta.enableRegionFailover=true`, 例如 + +```bash +helm install greptimedb greptime/greptimedb-cluster \ + --set meta.enableRegionFailover=true \ + ... +``` + +## Region Failover 的恢复用时 + +Region Failover 的恢复时间取决于: + +- 每个 Topic 的 region 数量 +- Kafka 集群的读取吞吐性能 + + +### 读放大 + +在最佳实践中,[Kafka 集群所支持的 topics/partitions 数量是有限的](https://docs.aws.amazon.com/msk/latest/developerguide/bestpractices.html)(超过这个数量可能会导致 Kafka 集群性能下降)。 +因此,GreptimeDB 允许多个 regions 共享一个 topic 作为 WAL,然而这可能会带来读放大的问题。 + +属于特定 Region 的数据由数据文件和 WAL 中的数据(通常为 WAL[LastCheckpoint...Latest])组成。特定 Region 的 failover 只需要读取该 Region 的 WAL 数据以重建内存状态,这被称为 Region 重放(region replaying)。然而,如果多个 Region 共享一个 Topic,则从 Topic 重放特定 Region 的数据需要过滤掉不相关的数据(即其他 Region 的数据)。这意味着从 Topic 重放特定 Region 的数据需要读取比该 Region 实际 WAL 数据大小更多的数据,这种现象被称为读取放大(read amplification)。 + +尽管多个 Region 共享同一个 Topic,可以让 Datanode 支持更多的 Region,但这种方法的代价是在 Region 重放过程中产生读取放大。 + +例如,为 [metasrv](/user-guide/deployments/configuration.md#metasrv-only-configuration) 配置 128 个 Topic,如果整个集群包含 1024 个 Region(物理 Region),那么每 8 个 Region 将共享一个 Topic。 + +![Read Amplification](/remote-wal-read-amplification.png) + +

(图 1:恢复 Region 3 需要读取比实际大小大 7 倍的冗余数据)

+ +估算读取放大倍数(重放数据大小/实际数据大小)的简单模型: + +- 对于单个 Topic,如果我们尝试重放属于该 Topic 的所有 Region,那么放大倍数将是 7+6+...+1 = 28 倍。(图 1 显示了 Region WAL 数据分布。重放 Region 3 将读取约为实际大小 7 倍的数据;重放 Region 6 将读取约为实际大小 6 倍的数据,以此类推) +- 在恢复 100 个 Region 时(需要大约 13 个 Topic),放大倍数大约为 28 \* 13 = 364 倍。 + +假设要恢复 100 个 Region,所有 Region 的实际数据大小是 0.5 GB,下表根据每个 Topic 的 Region 数量展示了数据重放的总量。 + +| 每个 Topic 的 Region 数量 | 100 个 Region 所需 Topic 数量 | 单个 Topic 读放大系数 | 总读放大系数 | 重放数据大小(GB) | +| ------------------------- | ----------------------------- | --------------------- | ------------ | ------------------ | +| 1 | 100 | 0 | 0 | 0.5 | +| 2 | 50 | 1 | 50 | 25.5 | +| 4 | 25 | 6 | 150 | 75.5 | +| 8 | 13 | 28 | 364 | 182.5 | +| 16 | 7 | 120 | 840 | 420.5 | + +下表展示了在 Kafka 集群在不同读取吞吐量情况下,100 个 region 的恢复时间。例如在提供 300MB/s 的读取吞吐量的情况下,恢复 100 个 Region 大约需要 10 分钟(182.5GB/0.3GB = 10 分钟)。 + +| 每个主题的区域数 | 重放数据大小(GB) | Kafka 吞吐量 300MB/s- 恢复时间(秒) | Kafka 吞吐量 1000MB/s- 恢复时间(秒) | +| ---------------- | ------------------ | ------------------------------------ | ------------------------------------- | +| 1 | 0.5 | 2 | 1 | +| 2 | 25.5 | 85 | 26 | +| 4 | 75.5 | 252 | 76 | +| 8 | 182.5 | 608 | 183 | +| 16 | 420.5 | 1402 | 421 | + + +### 改进恢复时间的建议 + +在上文中我们根据不同的每个 Topic 包含的 Region 数量计算了恢复时间以供参考。 +在实际场景中,读取放大的现象可能会比这个模型更为严重。 +如果您对恢复时间非常敏感,我们建议每个 Region 都有自己的 Topic(即,每个 Topic 包含的 Region 数量为 1)。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/user-guide/operations/region-migration.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/administration/manage-data/region-migration.md similarity index 71% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7/user-guide/operations/region-migration.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/administration/manage-data/region-migration.md index b6958f685..e7299121b 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/user-guide/operations/region-migration.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/administration/manage-data/region-migration.md @@ -1,3 +1,8 @@ +--- +keywords: [Region 迁移, 数据迁移, 负载均衡, 迁移请求, 迁移状态] +description: 介绍 Region 迁移功能及其在 GreptimeDB 中的应用,包括查询 Region 分布、选择迁移目标节点、发起迁移请求和查询迁移状态等内容。 +--- + # Region Migration Region 迁移允许用户在 Datanode 间移动 Region 数据。 @@ -18,7 +23,7 @@ Region 迁移允许用户在 Datanode 间移动 Region 数据。 ```sql select b.peer_id as datanode_id, a.greptime_partition_id as region_id -from information_schema.partitions a left join information_schema.greptime_region_peers b +from information_schema.partitions a left join information_schema.region_peers b on a.greptime_partition_id = b.region_id where a.table_name='migration_target' order by datanode_id asc; ``` @@ -32,6 +37,9 @@ on a.greptime_partition_id = b.region_id where a.table_name='migration_target' o 1 row in set (0.01 sec) ``` + +更多关于 `region_peers` 表的信息,请阅读 [REGION-PEERS](/reference/sql/information-schema/region-peers.md)。 + ## 选择 Region 迁移的目标节点 :::warning Warning 当起始节点等于目标节点时,Region 迁移不会被执行 @@ -41,13 +49,13 @@ on a.greptime_partition_id = b.region_id where a.table_name='migration_target' o 最后,你可以通过以下 SQL 请求发起 Region 迁移请求: ```sql -select migrate_region(4398046511104, 1, 2, 60); +ADMIN migrate_region(4398046511104, 1, 2, 60); ``` `migrate_region` 参数说明: ```sql -select migrate_region(region_id, from_peer_id, to_peer_id, replay_timeout); +ADMIN migrate_region(region_id, from_peer_id, to_peer_id, replay_timeout); ``` | Option | Description | Required | | @@ -56,3 +64,19 @@ select migrate_region(region_id, from_peer_id, to_peer_id, replay_timeout); | `from_peer_id` | 迁移起始节点(Datanode) 的 peer id。 | **Required** | | | `to_peer_id` | 迁移目标节点(Datanode) 的 peer id。 | **Required** | | | `replay_timeout` | 迁移时回放数据的超时时间(单位:秒)。如果新 Region 未能在指定时间内回放数据,迁移将失败,旧 Region 中的数据不会丢失。 | Optional | | + +## 查询迁移状态 + +`migrate_region` 函数将返回执行迁移的 Procedure Id,可以通过它查询过程状态: + +```sql +ADMIN procedure_state('538b7476-9f79-4e50-aa9c-b1de90710839') +``` + +如果顺利完成,将输出 JSON 格式的状态: + +```json + {"status":"Done"} +``` + +当然,最终可以通过从 `information_schema` 中查询 `region_peers` 和 `partitions` 来确认 Region 分布是否符合预期。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/administration/manage-data/table-sharding.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/administration/manage-data/table-sharding.md new file mode 100644 index 000000000..8e26b5946 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/administration/manage-data/table-sharding.md @@ -0,0 +1,194 @@ +--- +keywords: [表分片, 分区规则, 分布式表, 插入数据, 分布式查询] +description: 介绍表分片技术及其在 GreptimeDB 中的应用,包括分片时机、分区规则、创建分布式表、插入数据和分布式查询等内容。 +--- + +# 表分片 + +表分片是一种将大表分成多个小表的技术。 +这种做法通常用于提高数据库系统的性能。 + +在 GreptimeDB 中,数据从逻辑上被分片成多个分区。 +由于 GreptimeDB 使用“表”来分组数据并使用 SQL 来查询数据, +因此采用了 OLTP 数据库中常用的术语“分区”。 + +## 表分片的时机 + +在 GreptimeDB 中,数据管理和调度都是基于 region 级别的, +每个 region 对应一个表分区。 +因此,当你的表太大而无法放入单个节点, +或者表太热而无法由单个节点提供服务时, +应该考虑进行分片。 + +GreptimeDB 中的一个 region 具有相对固定的吞吐量, +表中的 region 数量决定了表的总吞吐量容量。 +如果你想增加表的吞吐量容量, +可以增加表中的 region 数量。 +理想情况下,表的整体吞吐量应与 region 的数量成正比。 + +至于使用哪个特定的分区列或创建多少个 region, +这取决于数据分布和查询模式。 +一个常见的目标是使数据在 region 之间的分布尽可能均匀。 +在设计分区规则集时应考虑查询模式, +因为一个查询可以在 region 之间并行处理。 +换句话说,查询延迟取决于“最慢”的 region 延迟。 + +请注意,region 数量的增加会带来一些基本的消耗并增加系统的复杂性。 +你需要考虑数据写入速率的要求、查询性能、存储系统上的数据分布。 +只有在必要时才应进行表分片。 + +有关分区和 region 之间关系的更多信息,请参阅贡献者指南中的[表分片](/contributor-guide/frontend/table-sharding.md)部分。 + +## 分区 + +在 GreptimeDB 中, +表可以通过多种方式进行水平分区, +并且它使用与 MySQL 相同的分区类型(及相应的语法)。 +目前,GreptimeDB 支持 RANGE COLUMNS 分区。 + +每个分区仅包含表中的一部分数据, +并按某些列的值范围进行分组。 +例如,我们可以在 GreptimeDB 中这样分区一个表: + +```sql +CREATE TABLE (...) +PARTITION ON COLUMNS () ( + +); +``` + +该语法主要由两部分组成: + +1. `PARTITION ON COLUMNS` 后跟一个用逗号分隔的列名列表,指定了将用于分区的列。这里指定的列必须是 Tag 类型(由 PRIMARY KEY 指定)。请注意,所有分区的范围必须**不能**重叠。 + +2. `RULE LIST` 是多个分区规则的列表。每个规则是分区名称和分区条件的组合。这里的表达式可以使用 `=`, `!=`, `>`, `>=`, `<`, `<=`, `AND`, `OR`, 列名和字面量。 + +:::tip 提示 +目前在 “PARTITION BY RANGE” 语法中不支持表达式。 +::: + +### 示例 + +## 创建分布式表 + +你可以使用 MySQL CLI [连接到 GreptimeDB](/user-guide/protocols/mysql.md) 并创建一个分布式表。 +下方的示例创建了一个表并基于 `device_id` 列进行分区。 + +```SQL +CREATE TABLE sensor_readings ( + device_id INT16, + reading_value FLOAT64, + ts TIMESTAMP DEFAULT current_timestamp(), + PRIMARY KEY (device_id), + TIME INDEX (ts) +) +PARTITION ON COLUMNS (device_id) ( + device_id < 100, + device_id >= 100 AND device_id < 200, + device_id >= 200 +); +``` + +你可以使用更多的分区列来创建更复杂的分区规则: + +```sql +CREATE TABLE sensor_readings ( + device_id INT, + area STRING, + reading_value FLOAT64, + ts TIMESTAMP DEFAULT current_timestamp(), + PRIMARY KEY (device_id, area), + TIME INDEX (ts) +) +PARTITION ON COLUMNS (device_id, area) ( + device_id < 100 AND area = 'North', + device_id < 100 AND area = 'South', + device_id >= 100 AND area = 'East', + device_id >= 100 AND area = 'West' +); +``` + +以下内容以具有两个分区列的 `sensor_readings` 表为例。 + +## 向表中插入数据 + +以下代码向 `sensor_readings` 表的每个分区插入 3 行数据。 + +```sql +INSERT INTO sensor_readings (device_id, area, reading_value, ts) +VALUES (1, 'North', 22.5, '2023-09-19 08:30:00'), + (10, 'North', 21.8, '2023-09-19 09:45:00'), + (50, 'North', 23.4, '2023-09-19 10:00:00'); + +INSERT INTO sensor_readings (device_id, area, reading_value, ts) +VALUES (20, 'South', 20.1, '2023-09-19 11:15:00'), + (40, 'South', 19.7, '2023-09-19 12:30:00'), + (90, 'South', 18.9, '2023-09-19 13:45:00'); + +INSERT INTO sensor_readings (device_id, area, reading_value, ts) +VALUES (110, 'East', 25.3, '2023-09-19 14:00:00'), + (120, 'East', 26.5, '2023-09-19 15:30:00'), + (130, 'East', 27.8, '2023-09-19 16:45:00'); + +INSERT INTO sensor_readings (device_id, area, reading_value, ts) +VALUES (150, 'West', 24.1, '2023-09-19 17:00:00'), + (170, 'West', 22.9, '2023-09-19 18:15:00'), + (180, 'West', 23.7, '2023-09-19 19:30:00'); +``` + +## 分布式查询 + +只需使用 `SELECT` 语法查询数据: + +```sql +SELECT * FROM sensor_readings order by reading_value desc LIMIT 5; +``` + +```sql ++-----------+------+---------------+---------------------+ +| device_id | area | reading_value | ts | ++-----------+------+---------------+---------------------+ +| 130 | East | 27.8 | 2023-09-19 16:45:00 | +| 120 | East | 26.5 | 2023-09-19 15:30:00 | +| 110 | East | 25.3 | 2023-09-19 14:00:00 | +| 150 | West | 24.1 | 2023-09-19 17:00:00 | +| 180 | West | 23.7 | 2023-09-19 19:30:00 | ++-----------+------+---------------+---------------------+ +5 rows in set (0.02 sec) +``` + +```sql +SELECT MAX(reading_value) AS max_reading +FROM sensor_readings; +``` + +```sql ++-------------+ +| max_reading | ++-------------+ +| 27.8 | ++-------------+ +1 row in set (0.03 sec) +``` + +```sql +SELECT * FROM sensor_readings +WHERE area = 'North' AND device_id < 50; +``` + +```sql ++-----------+-------+---------------+---------------------+ +| device_id | area | reading_value | ts | ++-----------+-------+---------------+---------------------+ +| 10 | North | 21.8 | 2023-09-19 09:45:00 | +| 1 | North | 22.5 | 2023-09-19 08:30:00 | ++-----------+-------+---------------+---------------------+ +2 rows in set (0.03 sec) +``` + +## 检查分片表 + +GreptimeDB 提供了几个系统表来检查数据库的状态。 +对于表分片信息,你可以查询 [`information_schema.partitions`](/reference/sql/information-schema/partitions.md), +它提供了一个表内分区的详细信息, +以及 [`information_schema.region_peers`](/reference/sql/information-schema/region-peers.md) 提供了 region 的运行时分布信息。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/user-guide/operations/monitoring.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/administration/monitoring/export-metrics.md similarity index 87% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7/user-guide/operations/monitoring.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/administration/monitoring/export-metrics.md index 8f476f7e1..e7537d77a 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/user-guide/operations/monitoring.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/administration/monitoring/export-metrics.md @@ -1,6 +1,11 @@ -# 监控 +--- +keywords: [导出指标, Prometheus, 监控指标, self_import, remote_write] +description: 介绍如何导出 GreptimeDB 的监控指标到 Prometheus 或 GreptimeDB 自身,并提供各组件的指标详情。 +--- -监控是数据库管理的重要组成部分。通过监控指标,你可以评估数据库的状态,维护部署并诊断问题。 +# 导出指标 + +通过监控指标,你可以评估数据库的状态,维护部署并诊断问题。 请参考[指标详情](#指标详情)章节了解 GreptimeDB 的具体指标。 @@ -36,10 +41,14 @@ docker run \ prom/prometheus ``` +:::tip NOTE +为了防止不小心退出 Docker 容器,你可能想以 “detached” 模式运行它:在 `docker run` 命令中添加 `-d` 参数即可。 +::: + ## 将指标保存到 GreptimeDB 自身 你还可以将指标保存到 GreptimeDB 本身,以便于使用 SQL 语句进行查询和分析。 -本节提供了相关配置示例,有关配置的更多详细信息,请参阅[监控指标选项](./configuration.md#monitor-metrics-options)。 +本节提供了相关配置示例,有关配置的更多详细信息,请参阅[监控指标选项](/user-guide/deployments/configuration.md#monitor-metrics-options)。 ### 单机模式 @@ -89,7 +98,7 @@ url = "http://127.0.0.1:4000/v1/prometheus/write?db=system" ``` GreptimeDB 兼容 Prometheus Remote-Write 协议。 -请参考 [Prometheus Remote-Write](/user-guide/write-data/prometheus.md) 获取更多信息。 +请参考 [Prometheus Remote-Write](/user-guide/ingest-data/for-observerbility/prometheus.md) 获取更多信息。 ## 指标详情 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/administration/monitoring/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/administration/monitoring/overview.md new file mode 100644 index 000000000..ca535b6fc --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/administration/monitoring/overview.md @@ -0,0 +1,13 @@ +--- +keywords: [监控, 数据库监控, 导出指标, 链路追踪, Prometheus] +description: 介绍监控 GreptimeDB 的方法,包括导出指标和链路追踪。 +--- + +# 概述 + +数据库的有效管理在很大程度上依赖于监控。 +你可以使用以下方法监控 GreptimeDB: + +- [导出指标](export-metrics.md) +- [链路追踪](tracing.md) + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/user-guide/operations/tracing.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/administration/monitoring/tracing.md similarity index 89% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7/user-guide/operations/tracing.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/administration/monitoring/tracing.md index 16fb8ea48..e4700fb6e 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/user-guide/operations/tracing.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/administration/monitoring/tracing.md @@ -1,8 +1,13 @@ -# Tracing +--- +keywords: [链路追踪, 分布式追踪, Jaeger, OTLP 协议, tracing 采样率] +description: 介绍 GreptimeDB 的分布式链路追踪功能,包括如何使用 Jaeger 进行追踪和配置 tracing 采样率。 +--- + +# 链路追踪 GreptimeDB 支持分布式链路追踪。 GreptimeDB 使用基于 gRPC 的 OTLP 协议导出所有采集到的 Span。您可以使用 [Jaeger](https://www.jaegertracing.io/)、[Tempo](https://grafana.com/oss/tempo/) 等支持基于 gRPC 的 OTLP 协议后端接收 GreptimeDB 采集到的 Span。 -在配置中的 [logging 部分](./configuration.md#logging-选项) 有对 tracing 的相关配置项说明,[standalone.example.toml](https://github.com/GreptimeTeam/greptimedb/blob/main/config/standalone.example.toml) 的 logging 部分提供了参考配置项。 +在配置中的 [logging 部分](/user-guide/deployments/configuration.md#logging-选项) 有对 tracing 的相关配置项说明,[standalone.example.toml](https://github.com/GreptimeTeam/greptimedb/blob/main/config/standalone.example.toml) 的 logging 部分提供了参考配置项。 ## 教程:使用 Jaeger 追踪 GreptimeDB 调用链路 @@ -45,7 +50,7 @@ enable_otlp_tracing = true greptime standalone start -c config.toml ``` -参考章节 [Mysql](../clients/mysql.md) 如何连接到 GreptimeDB。在 Mysql Client 中运行下面的 SQL 语句: +参考章节 [Mysql](/user-guide/protocols/mysql.md) 如何连接到 GreptimeDB。在 Mysql Client 中运行下面的 SQL 语句: ```sql CREATE TABLE host ( diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/administration/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/administration/overview.md new file mode 100644 index 000000000..e37d1dfc5 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/administration/overview.md @@ -0,0 +1,19 @@ +--- +keywords: [管理策略, 安装, 容量规划, 数据管理, 配置, 灾难恢复, 监控, 性能调优, 升级, 运行时信息] +description: 介绍 GreptimeDB 管理中的策略和实践,包括安装、容量规划、数据管理、配置、灾难恢复、监控和升级等内容。 +--- + +# 概述 + +本文档介绍了在 GreptimeDB 管理中使用的策略和实践。 + +* [安装](/getting-started/installation/overview.md) GreptimeDB 和 [g-t-control](/reference/gtctl.md) 命令行工具 +* 根据工作负载进行 GreptimeDB 的[容量规划](/user-guide/administration/capacity-plan.md) +* [管理数据](/user-guide/administration/manage-data/overview.md) 以避免数据丢失、降低成本和提高性能 +* 数据库配置,请阅读[配置](/user-guide/deployments/configuration.md)参考文档 +* GreptimeDB 的[灾难恢复方案](/user-guide/administration/disaster-recovery/overview.md) +* 通过[设置 Remote WAL](./remote-wal/quick-start.md) 实现 GreptimeDB 的集群容灾 +* GreptimeDB 的[监控指标](/user-guide/administration/monitoring/export-metrics.md)和[链路追踪](/user-guide/administration/monitoring/tracing.md) +* [性能调优技巧](/user-guide/administration/performance-tuning-tips.md) +* [升级](/user-guide/administration/upgrade.md) GreptimeDB 到新版本 +* 获取集群的[运行时信息](/user-guide/administration/runtime-info.md) diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/administration/performance-tuning-tips.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/administration/performance-tuning-tips.md new file mode 100644 index 000000000..b3e5ceeec --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/administration/performance-tuning-tips.md @@ -0,0 +1,212 @@ +--- +keywords: [性能调优, 查询性能, 缓存配置, 写入优化, 表结构设计, 指标监控, 对象存储, 批量写入, append-only 表] +description: 提供 GreptimeDB 性能调优的技巧,包括查询性能指标、缓存配置、写入优化和表结构设计建议。 +--- + +# 性能调优技巧 + +GreptimeDB 实例的默认配置可能不适合所有场景。因此根据场景调整数据库配置和使用方式相当重要。 + +GreptimeDB 提供了各种指标来帮助监控和排查性能问题。官方仓库里提供了用于独立模式和集群模式的 [Grafana dashboard 模版](https://github.com/GreptimeTeam/greptimedb/tree/main/grafana)。 + +## 查询 + +### 指标 + +以下指标可用于诊断查询性能问题: +| 指标 | 类型 | 描述 | +|---|---|---| +| greptime_mito_read_stage_elapsed_bucket | histogram | 存储引擎中查询不同阶段的耗时。 | +| greptime_mito_cache_bytes | gauge | 缓存内容的大小 | +| greptime_mito_cache_hit | counter | 缓存命中总数 | +| greptime_mito_cache_miss | counter | 缓存未命中总数 | + + +### 为对象存储开启缓存 + +我们推荐在使用对象存储时启用读取缓存和写入缓存。这可以将查询耗时缩短 10 倍以上。 + +> 提示: 从 v0.11 版本开始,在使用远程对象存储服务时,系统会默认启用本地缓存(包括读取和写入)。通常情况下,您只需要根据需求调整缓存容量即可。 + +读取缓存将对象或一段范围的数据存储在本地磁盘上,以避免再次从远程读取相同的数据。以下示例展示了如何为 S3 启用读取缓存。 +- `cache_path` 是存储缓存对象的目录,从 v0.11 版本开始不再需要手动设置。 +- `cache_capacity` 是缓存的容量。从 0.11 版本开始,默认初始值为 `5GiB`,建议至少留出总磁盘空间的 1/10 用于缓存。 + +```toml +[storage] +type = "S3" +bucket = "ap-southeast-1-test-bucket" +root = "your-root" +access_key_id = "****" +secret_access_key = "****" +endpoint = "https://s3.amazonaws.com/" +region = "your-region" +# 在 v0.11 前需要设置该路径 +# cache_path = "/path/to/s3cache" +cache_capacity = "10G" +``` + +写入缓存起到 write-through 缓存的作用,在将文件上传到对象存储之前,会先将它们存储在本地磁盘上。这可以减少第一次查询的延迟。 + + +以下示例展示了在 `v0.12` 版本之前如何启用写入缓存。 +- `enable_experimental_write_cache` 开关可用来启用写入缓存。从 `v0.11` 版本开始,当配置对象存储服务的时候,该值将默认设置为 `true`,即启用。 +- `experimental_write_cache_size` 用来设置缓存的容量。从 0.11 版本开始,默认初始值为 `5GiB`。 +- `experimental_write_cache_path` 用来设置存储缓存文件的路径。默认情况下它位于数据主目录下。 +- `experimental_write_cache_ttl` 用来设置缓存文件的 TTL。 + + +```toml +[[region_engine]] +[region_engine.mito] +enable_experimental_write_cache = true +experimental_write_cache_size = "10G" +experimental_write_cache_ttl = "8h" +# experimental_write_cache_path = "/path/to/write/cache" +``` + +### 增大缓存大小 + +可以监控 `greptime_mito_cache_bytes` 和 `greptime_mito_cache_miss` 指标来确定是否需要增加缓存大小。这些指标中的 `type` 标签表示缓存的类型。 + +如果 `greptime_mito_cache_miss` 指标一直很高并不断增加,或者 `greptime_mito_cache_bytes` 指标达到缓存容量,可能需要调整存储引擎的缓存大小配置。 + +以下是一个例子: + + +```toml +[[region_engine]] +[region_engine.mito] +# 写入缓存的缓存大小。此缓存的 `type` 标签值为 `file`。 +write_cache_size = "10G" +# SST 元数据的缓存大小。此缓存的 `type` 标签值为 `sst_meta`。 +sst_meta_cache_size = "128MB" +# 向量和箭头数组的缓存大小。此缓存的 `type` 标签值为 `vector`。 +vector_cache_size = "512MB" +# SST 行组页面的缓存大小。此缓存的 `type` 标签值为 `page`。 +page_cache_size = "512MB" +# 时间序列查询结果(例如 `last_value()`)的缓存大小。此缓存的 `type` 标签值为 `selector_result`。 +selector_result_cache_size = "512MB" + +[region_engine.mito.index] +## 索引暂存目录的最大容量。 +staging_size = "10GB" +``` + + + +对于 `v0.12` 之前的版本 + +```toml +[[region_engine]] +[region_engine.mito] +# 如果使用对象存储则取消该参数的注释 +# enable_experimental_write_cache = true +# 写入缓存的缓存大小。此缓存的 `type` 标签值为 `file`。 +experimental_write_cache_size = "10G" +# SST 元数据的缓存大小。此缓存的 `type` 标签值为 `sst_meta`。 +sst_meta_cache_size = "128MB" +# 向量和箭头数组的缓存大小。此缓存的 `type` 标签值为 `vector`。 +vector_cache_size = "512MB" +# SST 行组页面的缓存大小。此缓存的 `type` 标签值为 `page`。 +page_cache_size = "512MB" +# 时间序列查询结果(例如 `last_value()`)的缓存大小。此缓存的 `type` 标签值为 `selector_result`。 +selector_result_cache_size = "512MB" + +[region_engine.mito.index] +## 索引暂存目录的最大容量。 +staging_size = "10GB" +``` + +一些建议: +- 至少将写入缓存设置为磁盘空间的 1/10 +- 如果数据库内存使用率低于 20%,则可以至少将 `page_cache_size` 设置为总内存大小的 1/4 +- 如果缓存命中率低于 50%,则可以将缓存大小翻倍 +- 如果使用全文索引,至少将 `staging_size` 设置为磁盘空间的 1/10 + + +### 避免将高基数的列放到主键中 + +将高基数的列,如 `trace_id` 和 `uuid` 等列设置为主键会降低写入和查询的性能。建议建表时使用 [append-only](/reference/sql/create.md#创建-append-only-表) 表并将这些高基数的列设置为 fields。 + + +### 尽可能使用 append-only 表 + +一般来说,append-only 表具有更高的扫描性能,因为存储引擎可以跳过合并和去重操作。此外,如果表是 append-only 表,查询引擎可以使用统计信息来加速某些查询。 + +如果表不需要去重或性能优先于去重,我们建议为表启用 [append_mode](/reference/sql/create.md#创建-append-only-表)。例如,日志表应该是 append-only 表,因为日志消息可能具有相同的时间戳。 + + +## 写入 + +### 指标 + +以下指标有助于诊断写入问题: + +| 指标 | 类型 | 描述 | +|---|---|---| +| greptime_mito_write_stage_elapsed_bucket | histogram | 存储引擎中处理写入请求的不同阶段的耗时 | +| greptime_mito_write_buffer_bytes | gauge | 当前为写入缓冲区(memtables)分配的字节数(估算) | +| greptime_mito_write_rows_total | counter | 写入存储引擎的行数 | +| greptime_mito_write_stall_total | gauge | 当前由于内存压力过高而被阻塞的行数 | +| greptime_mito_write_reject_total | counter | 由于内存压力过高而被拒绝的行数 | +| raft_engine_sync_log_duration_seconds_bucket | histogram | 将 WAL 刷入磁盘的耗时 | +| greptime_mito_flush_elapsed | histogram | 刷入 SST 文件的耗时 | + + +### 批量写入行 + +批量写入是指通过同一个请求将多行数据发送到数据库。这可以显著提高写入吞吐量。建议的起始值是每批 1000 行。如果延迟和资源使用仍然可以接受,可以扩大攒批大小。 + +### 按时间窗口写入 +虽然 GreptimeDB 可以处理乱序数据,但乱序数据仍然会影响性能。GreptimeDB 从写入的数据中推断出时间窗口的大小,并根据时间戳将数据划分为多个时间窗口。如果写入的行不在同一个时间窗口内,GreptimeDB 需要将它们拆分,这会影响写入性能。 + +通常,实时数据不会出现上述问题,因为它们始终使用最新的时间戳。如果需要将具有较长时间范围的数据导入数据库,我们建议提前创建表并 [指定 compaction.twcs.time_window 选项](/reference/sql/create.md#创建自定义-compaction-参数的表)。 + + +## 表结构 + +### 使用多值 + +在设计架构时,我们建议将可以一起收集的相关指标放在同一个表中。这也可以提高写入吞吐量和压缩率。 + + +例如,以下三个表收集了 CPU 的使用率指标。 + +```sql +CREATE TABLE IF NOT EXISTS cpu_usage_user ( + hostname STRING NULL, + usage_value BIGINT NULL, + ts TIMESTAMP(9) NOT NULL, + TIME INDEX (ts), + PRIMARY KEY (hostname) +); +CREATE TABLE IF NOT EXISTS cpu_usage_system ( + hostname STRING NULL, + usage_value BIGINT NULL, + ts TIMESTAMP(9) NOT NULL, + TIME INDEX (ts), + PRIMARY KEY (hostname) +); +CREATE TABLE IF NOT EXISTS cpu_usage_idle ( + hostname STRING NULL, + usage_value BIGINT NULL, + ts TIMESTAMP(9) NOT NULL, + TIME INDEX (ts), + PRIMARY KEY (hostname) +); +``` + +我们可以将它们合并为一个具有三个字段的表。 + +```sql +CREATE TABLE IF NOT EXISTS cpu ( + hostname STRING NULL, + usage_user BIGINT NULL, + usage_system BIGINT NULL, + usage_idle BIGINT NULL, + ts TIMESTAMP(9) NOT NULL, + TIME INDEX (ts), + PRIMARY KEY (hostname) +); +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/user-guide/operations/remote-wal/cluster-deployment.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/administration/remote-wal/cluster-deployment.md similarity index 92% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7/user-guide/operations/remote-wal/cluster-deployment.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/administration/remote-wal/cluster-deployment.md index f2843b69e..20eb3a546 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/user-guide/operations/remote-wal/cluster-deployment.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/administration/remote-wal/cluster-deployment.md @@ -1,3 +1,8 @@ +--- +keywords: [集群部署, Kubernetes, GreptimeDB Operator, etcd 集群, Kafka 集群, Remote WAL, 数据写入, 数据查询] +description: 介绍如何在 Kubernetes 中部署带有 Remote WAL 配置的 GreptimeDB 集群,包括部署 GreptimeDB Operator、etcd 集群、Kafka 集群和 GreptimeDB 集群。 +--- + # 集群部署 我们强烈建议将 GreptimeDB 集群部署在 Kubernetes 中,这里是一些此次部署的前置依赖: @@ -91,8 +96,8 @@ metadata: strimzi.io/kraft: enabled spec: kafka: - version: 3.7.0 - metadataVersion: 3.7-IV4 + version: 3.9.0 + metadataVersion: "3.9" listeners: - name: plain port: 9092 @@ -177,7 +182,7 @@ my-cluster 1 3 1 Running latest 5m30s ## Step 5: 写入和读取数据 -你可以参考 [Overview](/getting-started/quick-start/overview.md) 来获得更多案例. 对于这个指南,我们将选用 MySQL 协议来连接数据库集群。 +我们将选用 MySQL 协议来连接数据库集群。 使用 kubectl 的 port forward 来转发 `4002` 流量: @@ -193,7 +198,7 @@ mysql -h 127.0.0.1 -P 4002 创建分布式表: -``` +```sql CREATE TABLE dist_table( ts TIMESTAMP DEFAULT current_timestamp(), n INT, @@ -205,8 +210,7 @@ PARTITION ON COLUMNS (n) ( n < 5, n >= 5 AND n < 9, n >= 9 -) -engine=mito; +); ``` 写入数据: diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/user-guide/operations/remote-wal/quick-start.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/administration/remote-wal/quick-start.md similarity index 88% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7/user-guide/operations/remote-wal/quick-start.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/administration/remote-wal/quick-start.md index 752883893..7ebeebb27 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/user-guide/operations/remote-wal/quick-start.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/administration/remote-wal/quick-start.md @@ -1,3 +1,8 @@ +--- +keywords: [快速开始, Remote WAL, Docker, Kafka 服务, Standalone GreptimeDB, 数据写入, 数据查询, Kafka Topics] +description: 介绍如何使用 Docker 快速启动带有 Remote WAL 的 Standalone GreptimeDB,包括创建自定义 Docker bridge、启动 Kafka 服务和 GreptimeDB。 +--- + # 快速开始 ## 什么是 Remote WAL @@ -42,6 +47,10 @@ docker run \ bitnami/kafka:3.6.0 ``` +:::tip NOTE +为了防止不小心退出 Docker 容器,你可能想以 “detached” 模式运行它:在 `docker run` 命令中添加 `-d` 参数即可。 +::: + 数据将保存在 `$(pwd)/kafka-data`. ### Step 3: 用 Remote WAL 模式启动 standalone 模式 GreptimeDB @@ -51,7 +60,7 @@ docker run \ ``` docker run \ --network greptimedb-remote-wal \ - -p 4000-4003:4000-4003 -p 4242:4242 \ + -p 4000-4003:4000-4003 \ -v "$(pwd)/greptimedb:/tmp/greptimedb" \ --name greptimedb --rm \ -e GREPTIMEDB_STANDALONE__WAL__PROVIDER="kafka" \ @@ -60,10 +69,12 @@ docker run \ --http-addr 0.0.0.0:4000 \ --rpc-addr 0.0.0.0:4001 \ --mysql-addr 0.0.0.0:4002 \ - --postgres-addr 0.0.0.0:4003 \ - --opentsdb-addr 0.0.0.0:4242 + --postgres-addr 0.0.0.0:4003 ``` +:::tip NOTE +为了防止不小心退出 Docker 容器,你可能想以 “detached” 模式运行它:在 `docker run` 命令中添加 `-d` 参数即可。 +::: 我们使用环境变量来指定 provider: diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/administration/runtime-info.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/administration/runtime-info.md new file mode 100644 index 000000000..0fcdf0348 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/administration/runtime-info.md @@ -0,0 +1,30 @@ +--- +keywords: [运行时信息, INFORMATION_SCHEMA, 系统元数据, 集群拓扑, Region 分布, 查询示例, 元数据访问] +description: 介绍如何通过 INFORMATION_SCHEMA 数据库访问系统元数据,并提供查询集群拓扑信息和表的 Region 分布的示例。 +--- + +# 运行时信息 + +`INFORMATION_SCHEMA` 数据库提供了对系统元数据的访问,如数据库或表的名称、列的数据类型等。 + +* 通过 [CLUSTER_INFO](/reference/sql/information-schema/cluster-info.md) 表查找集群的拓扑信息。 +* 通过 [PARTITIONS](/reference/sql/information-schema/partitions.md) 表和[REGION_PEERS](/reference/sql/information-schema/region-peers.md) 表查找表的 Region 分布。 + +例如查询一张表的所有 Region Id: + +```sql +SELECT greptime_partition_id FROM PARTITIONS WHERE table_name = 'monitor' +``` + +查询一张表的 region 分布在哪些 datanode 上: + +```sql +SELECT b.peer_id as datanode_id, + a.greptime_partition_id as region_id +FROM information_schema.partitions a LEFT JOIN information_schema.region_peers b +ON a.greptime_partition_id = b.region_id +WHERE a.table_name='monitor' +ORDER BY datanode_id ASC +``` + +请阅读[参考文档](/reference/sql/information-schema/overview.md)获取更多关于 `INFORMATION_SCHEMA` 数据库的信息。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/administration/upgrade.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/administration/upgrade.md new file mode 100644 index 000000000..641ee7aa5 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/administration/upgrade.md @@ -0,0 +1,184 @@ +--- +keywords: [版本升级, 内置工具, CLI 工具, 迁移升级, 导出数据, 导入数据, 升级步骤, 数据库升级] +description: 介绍如何使用内置工具将 GreptimeDB 从 v0.4 及以上版本升级到最新版本,包括 CLI 工具的使用和具体步骤。 +--- + +# 版本升级 + +从 `v0.4` 开始,我们提供了一个内置的工具来帮助您将以前的 GreptimeDB 部署升级到最新版本。 +如果不同版本之间有 Breaking Change,我们都建议使用此方法在不同版本的 GreptimeDB 之间进行迁移升级。 + +此工具可以将 `v0.3.0` 以上的版本升级到最新版本。 + +## CLI + +该工具在 `greptime` 二进制文件中。在开始之前,您需要准备目标版本的二进制文件。 + +```shell +greptime cli export --help +``` + +帮助文档如下: + +```shell +greptime-cli-export + +USAGE: + greptime cli export [OPTIONS] --addr --output-dir --target + +OPTIONS: + --addr + Server address to connect + + --output-dir + Directory to put the exported data. E.g.: /tmp/greptimedb-export + + --database + The name of the catalog to export + + [default: greptime-*] + + -j, --export-jobs + Parallelism of the export + + [default: 1] + + --max-retry + Max retry times for each job + + [default: 3] + + -t, --target + Things to export + + [default: all] + + Possible values: + - schema: Export all table schemas, corresponding to `SHOW CREATE TABLE` + - data: Export all table data, corresponding to `COPY DATABASE TO` + - all: Export all table schemas and data at once + + --log-dir + + + --start-time + A half-open time range: [start_time, end_time). The start of the time range (time-index column) for data export + + --end-time + A half-open time range: [start_time, end_time). The end of the time range (time-index column) for data export + + --log-level + + + --auth-basic + The basic authentication for connecting to the server + + -h, --help + Print help (see a summary with '-h') + + -V, --version + Print version +``` + +这里解释一些重要选项的含义: + +- `-addr`:Frontend 节点或者 Standalone 进程的 http server 地址。 +- `-output-dir`:要放置导出数据的目录。需要是当前机器上的路径。导出的 SQL 文件将放在该目录中。 +- `-target`:指定要导出的数据。`schema` 选项会导出每个表的 `CREATE TABLE` 子句。`data` 选项会导出每个数据库的数据以及对应 DB 的 `COPY FROM` 语句。默认情况下会导出 `schema` 和 `data` 的所有数据,推荐不设定选项直接使用默认值以导出所有数据。 + +对于完整的升级,您需要使用每个目标选项两次执行此工具。 + +## 从 0.8.x 升级 + +这一节将演示如何从 `v0.8.x` 升级到 `v0.9.x`。 + +在下面的文本中,我们假设您的数据库的 HTTP 端口为 `127.0.0.1:4000`。 + +### 一次导出表结构和表数据 + +```shell +greptime cli export --addr '127.0.0.1:4000' --output-dir /tmp/greptimedb-export +``` + +如果成功,您将看到类似于以下内容的输出 + +```log +2024-08-01T06:32:26.547809Z INFO cmd: Starting app: greptime-cli +2024-08-01T06:32:27.239639Z INFO cmd::cli::export: Finished exporting greptime.greptime_private with 0 table schemas to path: /tmp/greptimedb-export/greptime/greptime_private/ +2024-08-01T06:32:27.540696Z INFO cmd::cli::export: Finished exporting greptime.pg_catalog with 0 table schemas to path: /tmp/greptimedb-export/greptime/pg_catalog/ +2024-08-01T06:32:27.832018Z INFO cmd::cli::export: Finished exporting greptime.public with 0 table schemas to path: /tmp/greptimedb-export/greptime/public/ +2024-08-01T06:32:28.272054Z INFO cmd::cli::export: Finished exporting greptime.test with 1 table schemas to path: /tmp/greptimedb-export/greptime/test/ +2024-08-01T06:32:28.272166Z INFO cmd::cli::export: Success 4/4 jobs, cost: 1.724222791s +2024-08-01T06:32:28.416532Z INFO cmd::cli::export: Executing sql: COPY DATABASE "greptime"."greptime_private" TO '/tmp/greptimedb-export/greptime/greptime_private/' WITH (FORMAT='parquet'); +2024-08-01T06:32:28.556017Z INFO cmd::cli::export: Finished exporting greptime.greptime_private data into path: /tmp/greptimedb-export/greptime/greptime_private/ +2024-08-01T06:32:28.556330Z INFO cmd::cli::export: Finished exporting greptime.greptime_private copy_from.sql +2024-08-01T06:32:28.556424Z INFO cmd::cli::export: Executing sql: COPY DATABASE "greptime"."pg_catalog" TO '/tmp/greptimedb-export/greptime/pg_catalog/' WITH (FORMAT='parquet'); +2024-08-01T06:32:28.738719Z INFO cmd::cli::export: Finished exporting greptime.pg_catalog data into path: /tmp/greptimedb-export/greptime/pg_catalog/ +2024-08-01T06:32:28.738998Z INFO cmd::cli::export: Finished exporting greptime.pg_catalog copy_from.sql +2024-08-01T06:32:28.739098Z INFO cmd::cli::export: Executing sql: COPY DATABASE "greptime"."public" TO '/tmp/greptimedb-export/greptime/public/' WITH (FORMAT='parquet'); +2024-08-01T06:32:28.875600Z INFO cmd::cli::export: Finished exporting greptime.public data into path: /tmp/greptimedb-export/greptime/public/ +2024-08-01T06:32:28.875888Z INFO cmd::cli::export: Finished exporting greptime.public copy_from.sql +2024-08-01T06:32:28.876005Z INFO cmd::cli::export: Executing sql: COPY DATABASE "greptime"."test" TO '/tmp/greptimedb-export/greptime/test/' WITH (FORMAT='parquet'); +2024-08-01T06:32:29.053681Z INFO cmd::cli::export: Finished exporting greptime.test data into path: /tmp/greptimedb-export/greptime/test/ +2024-08-01T06:32:29.054104Z INFO cmd::cli::export: Finished exporting greptime.test copy_from.sql +2024-08-01T06:32:29.054162Z INFO cmd::cli::export: Success 4/4 jobs, costs: 781.98875ms +2024-08-01T06:32:29.054181Z INFO cmd: Goodbye! + +``` + +此时输出目录的结构如下 + +```plaintext +/tmp/greptimedb-export/ +├── greptime/public +│   ├── copy_from.sql +│   ├── create_tables.sql +│   ├── up.parquet +│   └── other-tables.parquet +``` + +内容包括 `create_tables.sql`, `copy_from.sql` 和 DB `greptime-public` 的每个表的 parquet 文件。`create_tables.sql` 包含当前 DB 所有表的建表语句,`copy_from.sql` 则包含一条 `COPY DATABASE FROM` 的语句,用于将数据文件 COPY 到目标 DB。剩下的 parquet 个数的文件就是每个表的数据文件。 + +### 导入表结构和数据 + +然后您需要执行上一步生成的 SQL 文件。首先是 `create_tables.sql`。在之前的步骤中导出的 SQL 语句使用的是 PostgreSQL 方言,接下来的操作都将通过 [PostgreSQL 协议](/user-guide/protocols/postgresql.md)来进行。本文档假设客户端为 `psql`。 + +:::tip NOTICE +从这一步开始,所有的操作都是在新版本的 GreptimeDB 中完成的。 + +PostgreSQL 协议的默认端口是 `4003`。 +::: + +在执行以下命令之前,您需要在新部署中首先创建相应的数据库(但在本例中,数据库 `greptime-public` 是默认的)。 + +此命令将在新版本的 GreptimeDB 中创建所有表。 + +```shell +psql -h 127.0.0.1 -p 4003 -d public -f /tmp/greptimedb-export/greptime/public/create_tables.sql +``` + +接下来导入数据 + +```shell +psql -h 127.0.0.1 -p 4003 -d public -f /tmp/greptimedb-export/greptime/public/copy_from.sql +``` + +### 清理 + +到这一步,所有的数据都已经迁移完毕。您可以在新集群中检查数据。 + +在确认数据正确后,您可以清理旧集群和临时的 `--output-dir`。在本例中是 `/tmp/greptimedb-export`。 + +## 推荐流程 + +该部分给出了一个推荐的整体流程,以便平滑升级 GreptimeDB。如果您的环境可以在升级过程中离线,可以跳过此部分。 + +1. 创建一个全新的 v0.9.x 集群 +2. 使用 v0.9.x 版本的 cli 工具导出并导入 `create-table` +3. 将工作负载切换到新集群 +4. 使用 v0.9.x 版本的 cli 工具导出并导入 `database-data` + +注意 + +- 在步骤 2 和 3 之间对表结构的更改将丢失 +- 在第四部完成之前,老数据在新集群上是不可见的。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/user-guide/concepts/architecture.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/concepts/architecture.md similarity index 56% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7/user-guide/concepts/architecture.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/concepts/architecture.md index d3f606507..6485a56b2 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/user-guide/concepts/architecture.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/concepts/architecture.md @@ -1,13 +1,18 @@ +--- +keywords: [基础架构, Metasrv, Frontend, Datanodes, 集群, 路由, 监测, 伸缩扩容, 数据存储, 读写请求] +description: 介绍 GreptimeDB 的基础架构,包括 Metasrv、Frontend 和 Datanodes 三个主要组成部分及其功能。 +--- + # 基础架构 ![architecture](/architecture-3.png) -为了形成一个强大的数据库集群,并控制其复杂性,GreptimeDB 架构中有三个主要组成部分:Metasrv,Frontend 和 Datanodes。 +为了形成一个强大的数据库集群,并控制其复杂性,GreptimeDB 架构中有三个主要组成部分:Metasrv,Frontend 和 Datanode。 - [**Metasrv**](/contributor-guide/metasrv/overview.md) 控制着 GreptimeDB 集群的核心命令。在典型的部署结构中,至少需要三个节点才能建立一个可靠的 _Metasrv_ 小集群。_Metasrv_ 管理着数据库和表的信息,包括数据如何在集群中传递、请求的转发地址等。它还负责监测 `Datanode` 的可用性和性能,以确保路由表的最新状态和有效性。 -- [**Frontend**](/contributor-guide/frontend/overview.md) 作为无状态的组件,可以根据需求进行伸缩扩容。它负责接收请求并鉴权,将多种协议转化为 GreptimeDB 集群的内部协议,并根据 _Metasrv_ 中的信息将请求转发到相应的 _Datanode_。 +- [**Frontend**](/contributor-guide/frontend/overview.md) 作为无状态的组件,可以根据需求进行伸缩扩容。它负责接收请求并鉴权,将多种协议转化为 GreptimeDB 集群的内部 gRPC 协议,并根据 _Metasrv_ 中的表的分片路由信息将请求转发到相应的 _Datanode_。 -- [**Datanode**](/contributor-guide/datanode/overview.md) 负责 GreptimeDB 集群中的表的 `region` 数据存储,接收并执行从 _Frontend_ 发来的读写请求。 +- [**Datanode**](/contributor-guide/datanode/overview.md) 负责 GreptimeDB 集群中的表的 `region` 数据存储,接收并执行从 _Frontend_ 发来的读写请求,处理查询和写入,并返回对应的结果。 -通过灵活的架构设计,以上三个组件可以合并打包在一起,支持本地部署下的单机模式,我们称之为 standalone 模式。 +通过灵活的架构设计,以上三个组件既可以是集群分布式部署,也可以合并打包在一个二进制包内,支持本地部署下的单机模式,我们称之为 standalone 模式。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/concepts/data-model.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/concepts/data-model.md new file mode 100644 index 000000000..3efc7f1b0 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/concepts/data-model.md @@ -0,0 +1,86 @@ +--- +keywords: [数据模型, 表结构, 列类型, 设计考虑, 时序表, Tag 列, Timestamp 列, Field 列, Metric 表, Log 表] +description: 介绍 GreptimeDB 的数据模型,包括表的结构、列类型和设计考虑,适用于指标、日志和事件数据。 +--- + +# 数据模型 + +## 模型 + +GreptimeDB 使用时序表来进行数据的组织、压缩和过期管理。数据模型主要基于关系型数据库中的表模型,同时考虑到了指标(metrics)、日志(logs)及事件(events)数据的特点。 + +GreptimeDB 中的所有数据都被组织成表,每个表中的数据项由三种类型的列组成:`Tag`、`Timestamp` 和 `Field`。 + +- 表名通常与指标、日志的名称相同。 +- `Tag` 列中存储经常被查询的元数据,其中的值是数据源的标签,通常用于描述数据的特定特征。`Tag` 列具有索引,所以使用 `Tag` 列的查询具备良好的性能。 +- `Timestamp` 是指标、日志及事件的时序数据库的基础,它表示数据生成的日期和时间。Timestamp 具有索引,所以使用 `Timestamp` 的查询具有良好的性能。一个表只能有一个 `Timestamp` 列,被称为时间索引列。 +- 其他列是 `Field` 列,其中的值是被收集的数据指标或日志。这些指标通常是数值或字符串,但也可能是其他类型的数据,例如地理位置。`Field` 列默认情况下没有被索引,对该字段做过滤查询会全表扫描。这可能会消耗大量资源并且性能较差,但是字符串字段可以启用[全文索引](/user-guide/logs/query-logs.md#全文索引加速搜索),以加快日志搜索等查询的速度。 + +### Metric 表 + +假设我们有一个名为 `system_metrics` 的时间序列表用于监控独立设备的资源使用情况。 + +```sql +CREATE TABLE IF NOT EXISTS system_metrics ( + host STRING, + idc STRING, + cpu_util DOUBLE, + memory_util DOUBLE, + disk_util DOUBLE, + ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY(host, idc), + TIME INDEX(ts) +); +``` + +该表的数据模型如下: + +![time-series-table-model](/time-series-data-model.svg) + +这与大家熟悉的表模型非常相似。不同之处在于 `Timestamp` 约束,它用于将 `ts` 列指定为此表的时间索引列。 + +- 表名为 `system_metrics`。 +- 对于 `Tag` 列,`host` 列表示收集的独立机器的主机名,`idc` 列显示机器所在的数据中心。这些是查询元数据,可以在查询时有效地过滤数据。 +- `Timestamp` 列 `ts` 表示收集数据的时间。使用该列查询具有时间范围的数据时具备较高的性能。 +- `Field` 列中的 `cpu_util`、`memory_util`、`disk_util` 和 `load` 列分别表示机器的 CPU 利用率、内存利用率、磁盘利用率和负载。 + 这些列包含实际的数据并且不被索引,但是可以被高效地计算,例如求最大最小值、均值和百分比分布等。 + 请避免在查询条件中使用 `Field` 列,这会消耗大量资源并且性能较差。 + +### Log 表 + +你还可以创建一个日志表用于存储访问日志: + +```sql +CREATE TABLE access_logs ( + access_time TIMESTAMP TIME INDEX, + remote_addr STRING, + http_status STRING, + http_method STRING, + http_refer STRING, + user_agent STRING, + request STRING FULLTEXT, + PRIMARY KEY (http_status, http_method) +) with ('append_mode'='true'); +``` +其中: + +- 时间索引列为 `access_time`。 +- `http_status`、`http_method` 为 Tag。 +- `remote_addr`、`http_refer`、`user_agent`、`request` 为 Field。`request` 是通过 [`FULLTEXT` 列选项](/reference/sql/create.md#fulltext-列选项)启用全文索引的字段。 +- 这个表是一个用于存储日志的 [append-only 表](/reference/sql/create.md#创建-append-only-表)。它允许一个主键下存在重复的时间戳。 + +要了解如何指定 `Tag`、`Timestamp` 和 `Field` 列,请参见[表管理](/user-guide/administration/manage-data/basic-table-operations.md#创建表)和 [CREATE 语句](/reference/sql/create.md)。 + +当然,无论何时,你都可以将指标和日志放在一张表里,这也是 GreptimeDB 提供的关键能力。 + +## 设计考虑 + +GreptimeDB 基于表进行设计,原因如下: + +- 表格模型易于学习,具有广泛的用户群体,我们只需引入时间索引的概念即可实现对指标、日志和事件的统一。 +- Schema 是描述数据特征的元数据,对于用户来说更方便管理和维护。通过引入 Schema 版本的概念,我们可以更好地管理数据兼容性。 +- Schema 通过其类型、长度等信息带来了巨大的优化存储和计算的好处,我们可以进行有针对性的优化。 +- 当我们有了表格 Schema 后,自然而然地引入了 SQL,并用它来处理各种表之间的关联分析和聚合查询,为用户抵消了学习和使用成本。 +- 比起 OpenTSDB 和 Prometheus 采用的单值模型,GreptimeDB 使用多值模型使其中一行数据可以具有多列数据。多值模型面向数据源建模,一个 metric 可以有用 field 表示的值。多值模型的优势在于它可以一次性向数据库写入或读取多个值,从而减少传输流量并简化查询。相比之下,单值模型则需要将数据拆分成多个记录。阅读[博客](https://greptime.com/blogs/2024-05-09-prometheus)以获取更多详情。 + +GreptimeDB 使用 SQL 管理表 Schema。有关更多信息,请参见[表管理](/user-guide/administration/manage-data/basic-table-operations.md)。但是,我们对 Schema 的定义并不是强制性的,而是倾向于 **Schemaless** 的方式,类似于 MongoDB。有关更多详细信息,请参见[自动生成表结构](../ingest-data/overview.md#自动生成表结构)。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/concepts/features-that-you-concern.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/concepts/features-that-you-concern.md new file mode 100644 index 000000000..ad5a8cb48 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/concepts/features-that-you-concern.md @@ -0,0 +1,74 @@ +--- +keywords: [关键特性, 日志处理, 数据更新, 数据删除, TTL 策略, 压缩率, 高基数问题, 持续聚合, 云存储, 性能对比, 灾难恢复, 地理空间索引, JSON 数据] +description: 介绍 GreptimeDB 的关键特性,并解答用户关心的常见问题,如日志处理、数据更新和删除、TTL 策略等。 +--- + +# 关键特性 + +## GreptimeDB 支持处理日志或事件吗? + +是的,从 v0.9.0 版本开始,GreptimeDB 将所有时间序列视为具有时间戳的上下文事件,从而统一了指标、日志和事件的处理。它支持使用 SQL、PromQL 进行指标和事件分析,并支持通过持续聚合进行流式处理。 + +请阅读[日志处理使用指南](/user-guide/logs/overview.md)。 + +## GreptimeDB 支持更新数据吗? + +支持,请参考[更新数据](/user-guide/manage-data/overview.md#更新数据)获取更多信息。 + +## GreptimeDB 支持删除数据吗? + +支持,请参考[删除数据](/user-guide/ingest-data/overview.md#删除数据)获取更多信息。 + +## 我可以为不同的表或指标设置 TTL 或保留策略吗? + +当然。请参考[使用 TTL 策略保留数据](/user-guide/manage-data/overview.md#使用-ttl-策略保留数据)。 + +## GreptimeDB 的压缩率是多少? + +答案是视情况而定。 + +GreptimeDB 使用列式存储布局,并通过最佳算法压缩时间序列数据,并且它会根据列数据的统计和分布选择最合适的压缩算法。GreptimeDB 还将提供可以更紧凑地压缩数据但会失去精度的 Rollup 功能。 + +因此,GreptimeDB 的数据压缩率可能在 2 倍到几百倍之间,这取决于你的数据特性以及你是否可以接受精度损失。 + +## GreptimeDB 如何解决高基数问题? + +GreptimeDB 通过以下方式解决这个问题: + +- **分片**:它将数据和索引分布在不同的 Region 服务器之间。阅读 GreptimeDB 的[架构](./architecture.md)。 +- **智能索引**:它不强制为每个标签创建倒排索引,而是根据标签列的特性和负载类型选择合适的索引类型并自动构建,更多信息可以参考这篇[博客](https://greptime.com/blogs/2022-12-21-storage-engine-design#smart-indexing)。 +- **MPP**: 除了索引之外,查询引擎还会利用向量化执行和分布式并行执行等技术来加速查询。 + +## GreptimeDB 支持持续聚合或降采样吗? + +从 0.8 版本开始,GreptimeDB 添加了一个名为 `Flow` 的新功能,用于持续聚合和降采样等场景。请阅读[用户指南](/user-guide/flow-computation/overview.md)获取更多信息。 + +## 我可以在云的对象存储中存储数据吗? + +可以,GreptimeDB 的数据访问层基于 [OpenDAL](https://github.com/apache/incubator-opendal),它支持大多数类型的对象存储服务。 +数据可以存储在如 AWS S3 或 Azure Blob Storage 等性价比高的云存储服务中,请参考这里的存储[配置指南](./../deployments/configuration.md#storage-options)。 + +GreptimeDB 还提供一个完全托管的云服务 [GreptimeCloud](https://greptime.cn/product/cloud) 来帮助您管理云中的数据。 + +## GreptimeDB 对比其他存储或时序数据库的性能如何? + +请阅读以下性能报告: + +* [GreptimeDB vs. InfluxDB](https://greptime.cn/blogs/2024-08-08-report) +* [GreptimeDB vs. Grafana Mimir](https://greptime.cn/blogs/2024-08-01-grafana) +* [GreptimeDB vs. ClickHouse vs. ElasticSearch](https://greptime.cn/blogs/2024-08-21-report) +* [GreptimeDB vs. SQLite](https://greptime.cn/blogs/2024-08-30-sqlite) + +## GreptimeDB 有灾难恢复解决方案吗? + +有的,请参阅[灾难恢复文档](/user-guide/administration/disaster-recovery/overview.md)。 + +## GeptimeDB 有地理空间索引吗? + +我们提供 [内置函数](/reference/sql/functions/geo.md) 支持 Geohash, H3 and S2 索 +引。 + + +## GeptimeDB 支持 JSON 数据吗? + +我们提供 [内置函数](/reference/sql/functions/overview.md#json-functions) 支持访问 JSON 数据类型。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/concepts/key-concepts.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/concepts/key-concepts.md new file mode 100644 index 000000000..d0b9e403b --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/concepts/key-concepts.md @@ -0,0 +1,51 @@ +--- +keywords: [核心概念, 数据库, 时序表, 数据类型, 索引, 视图, Flow] +description: 介绍 GreptimeDB 的核心概念,包括数据库、时序表、数据类型、索引、视图和 Flow 等。 +--- + +# 核心概念 + +为了理解 GreptimeDB 如何管理和服务其数据,你需要了解这些 GreptimeDB 的构建模块。 + +## 数据库 + +类似于关系型数据库中的数据库,数据库是数据容器的最小单元,数据可以在这个单元中被管理和计算。 +你可以利用数据库来实现数据隔离,形成类似租户的效果。 + +## Time-Series Table + +GreptimeDB 将时序表设计为数据存储的基本单位。 +其类似于传统关系型数据库中的表,但需要一个时间戳列(我们称之为 `TIME INDEX`—— **时间索引**),并且该表持有一组共享一个共同 schema 的数据。 + +表是行和列的集合: + +* 行:表中水平方向的值的集合。 +* 列:表中垂直方向的值的集合,GreptimeDB 将列分为时间索引 Time Index、标签 Tag 和字段 Field。 + +你使用 SQL `CREATE TABLE` 创建表,或者使用[自动生成表结构](/user-guide/ingest-data/overview.md#自动生成表结构)功能通过输入的数据结构自动创建表。在分布式部署中,一个表可以被分割成多个分区,其位于不同的数据节点上。 + +关于时序表的数据模型的更多信息,请参考[数据模型](./data-model.md)。 + +## Table Region + +分布式表的每个分区被称为一个区域。一个区域可能包含一个连续数据的序列,这取决于分区算法,区域信息由 Metasrv 管理。这对发送写入和查询的用户来说是完全透明的。 + +## 数据类型 + +GreptimeDB 中的数据是强类型的,当创建表时,Auto-schema 功能提供了一些灵活性。当表被创建后,同一列的数据必须共享共同的数据类型。 + +在[数据类型](/reference/sql/data-types.md)中找到所有支持的数据类型。 + +## 索引 + +索引是一种性能调优方法,可以加快数据的更快地检索速度。 +GreptimeDB 提供多种类型的[索引](/user-guide/manage-data/data-index.md)来加速查询。 + +## View + +从 SQL 查询结果集派生的虚拟表。它像真实表一样包含行和列,但它本身不存储任何数据。 +每次查询视图时,都会从底层表中动态检索视图中显示的数据。 + +## Flow + +GreptimeDB 中的 Flow 是指[持续聚合](/user-guide/flow-computation/overview.md)过程,该过程根据传入数据持续更新和聚合数据。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/user-guide/concepts/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/concepts/overview.md similarity index 58% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7/user-guide/concepts/overview.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/concepts/overview.md index e9eaa1446..737fa1861 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/user-guide/concepts/overview.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/concepts/overview.md @@ -1,16 +1,22 @@ +--- +keywords: [特点, 优势, 数据模型, 基础架构, 存储位置, 核心概念, 关键特性] +description: 概述 GreptimeDB 的特点和优势,并提供相关文档链接,帮助用户了解 GreptimeDB 的设计和功能。 +--- + # 概述 -- [Why GreptimeDB](./why-greptimedb.md):介绍了 GreptimeDB 的特点和优势,包括其灵活的架构,允许在各种环境中部署,从嵌入式到云原生等。GreptimeDB 还具有成本效益、高性能和用户友好等特点。 +- [Why GreptimeDB](./why-greptimedb.md):介绍了 GreptimeDB 的特点和优势,包括其对指标、日志和事件数据的统一设计,云原生和灵活架构允许在各种环境中部署,从嵌入式到云平台等。GreptimeDB 还具有成本优势、高性能和用户友好等特点。 - [数据模型](./data-model.md):介绍了 GreptimeDB 的数据模型,包括表的模式、索引列等。 - [基础架构](./architecture.md):获取 GreptimeDB 的云原生架构。 - [存储位置](./storage-location.md):介绍了 GreptimeDB 的存储位置,包括本地磁盘、HDFS 、AWS S3 和阿里云 OSS 等云对象存储。 - [核心概念](./key-concepts.md):介绍了 GreptimeDB 的核心概念,包括表、时间索引约束、表Region 和数据类型等。 -- [关键特性](./features-that-you-concern.md): 介绍了一个 TSDB 用户较为关心的主要特性。 +- [关键特性](./features-that-you-concern.md): 介绍了 TSDB 用户较为关心的指标(metrics)、日志(logs)和事件(events)数据库的特性。 ## 阅读更多 从我们的博客文章中获取 GreptimeDB 路线图和架构设计: - [专为实时而生 — GreptimeDB 现已在 GitHub 正式开源](https://greptime.com/blogs/2022-11-15-this-time-for-real) +- [事件管理革命:监控系统中统一日志和指标](https://greptime.com/blogs/2024-06-25-logs-and-metrics) - [GreptimeDB 架构内幕:基于分布式、云原生原则设计,实现时序处理及分析融合](https://greptime.com/blogs/2022-12-08-GreptimeDB-internal-design) - [GreptimeDB 存储引擎设计内幕:针对时序场景,检索压缩更智能](https://greptime.com/blogs/2022-12-21-storage-engine-design) diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/concepts/storage-location.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/concepts/storage-location.md new file mode 100644 index 000000000..faacd9c34 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/concepts/storage-location.md @@ -0,0 +1,45 @@ +--- +keywords: [存储位置, 本地文件系统, 云存储, AWS S3, Azure Blob Storage, 阿里云 OSS, 存储文件结构] +description: 介绍 GreptimeDB 支持的存储位置,包括本地文件系统和各种云存储服务,以及存储文件结构。 +--- + +# 存储位置 + +GreptimeDB 支持将数据存储在本地文件系统、AWS S3 及其兼容服务(包括 minio、digitalocean space、腾讯云对象存储(COS)、百度云对象存储(BOS)等)、Azure Blob Storage 和阿里云 OSS 中。 + +## 本地文件结构 + +GreptimeDB 的存储文件结构包括以下内容: + +```cmd +├── metadata + ├── raftlog + ├── rewrite + └── LOCK +├── data +│   ├── greptime +│   └── public +├── logs +├── index_intermediate +│   └── staging +└── wal + ├── raftlog + ├── rewrite + └── LOCK +``` + +- `metadata`: 内部元数据目录,保存 catatalog、数据库以及表的元信息、procedure 状态等内部状态。在集群模式下,此目录不存在,因为所有这些状态(包括区域路由信息)都保存在 `Metasrv` 中。 +- `data`: 存储 GreptimeDB 的实际的时间序列数据和索引文件。如果要自定义此路径,请参阅 [存储选项](../deployments/configuration.md#storage-options)。该目录按照 catalog 和 schema 的两级结构组织。 +- `logs`: GreptimeDB 日志文件目录。 +- `wal`: 预写日志文件目录。 +- `index_intermediate`: 索引构建和查询相关的的临时中间数据目录。 + +## 云存储 + +文件结构中的 `cluster` 和 `data` 目录可以存储在云存储中。请参考[存储选项](../deployments/configuration.md#存储选项)了解更多细节。 + +请注意,仅将 `data` 目录存储在对象存储中不足以确保数据可靠性和灾难恢复,`wal` 和 `metadata` 也需要考虑灾难恢复,更详细地请参阅[灾难恢复文档](/user-guide/administration/disaster-recovery/overview.md)。 + +## 多存储引擎支持 + +GreptimeDB 的另一个强大功能是可以为每张表单独选择存储引擎。例如,您可以将一些表存储在本地磁盘上,将另一些表存储在 Amazon S3 或 Google Cloud Storage 中,请参考 [create table](/reference/sql/create.md#create-table)。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/concepts/why-greptimedb.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/concepts/why-greptimedb.md new file mode 100644 index 000000000..a7d68ace4 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/concepts/why-greptimedb.md @@ -0,0 +1,113 @@ +--- +keywords: [时序数据库, 云原生, 分布式, 高性能, 用户友好, 存算分离, PromQL, SQL, Python] +description: 介绍 GreptimeDB 的特点、设计原则和优势,包括统一指标、日志和事件,云原生设计,高性能和用户友好等。 +--- + +# 为什么选择 GreptimeDB + +GreptimeDB 是一个云原生、分布式和开源的时序数据库,旨在处理、存储和分析大量的指标、日志和事件数据(计划中还包括 Trace)。 +它在处理涉及时序和实时分析的混合处理工作负载方面非常高效,同时为开发者提供了极佳的体验。 + +可以阅读博客文章《[This Time, for Real](https://greptime.com/blogs/2022-11-15-this-time-for-real)》和《[Unifying Logs and Metrics](https://greptime.com/blogs/2024-06-25-logs-and-metrics)》了解我们开发 GreptimeDB 的动机。 +在这些文章中,我们深入探讨了 Greptime 高性能背后的原因以及一些突出的功能。 + +## 统一的指标、日志和事件 + +通过[时序表](./data-model.md)的模型设计、对 SQL 的原生支持以及存算分离架构带来的混合工作负载, +GreptimeDB 可以同时处理指标、日志和事件, +增强不同时间序列数据之间的关联分析, +并简化架构、部署成本和 API。 + +阅读 [SQL 示例](/user-guide/overview.md#sql-query-example) 了解详细信息。 + +## 可用性、可扩展性和弹性 + +从第一天起,GreptimeDB 就按照云原生数据库的原则设计,这意味着它能够充分利用云的优势。其一些好处包括: + +1. 高可用的按需计算资源,目标是实现 99.999% 的可用性和正常运行时间,即每年大约只有五分钟十五秒的停机时间。 +2. 弹性和可扩展性,允许开发者根据使用情况轻松扩展或缩减、添加或移动资源。 +3. 高可靠性和容错性以防止数据丢失。系统的目标是实现 99.9999% 的可用性率。 + +这些功能共同确保 GreptimeDB 始终提供最佳的性能。 +下面是关于如何实现这些功能的额外技术解释。 + +### 可弹性扩展的资源隔离 + +![存储/计算分离,计算/计算分离](/storage-compute-disaggregation-compute-compute-separation.png) + +存储和计算资源是分离的,允许每个资源独立扩展、消耗和定价。 +这不仅大大提高了计算资源的利用率,还适配了“按需付费”的定价模式,避免了资源未充分利用的浪费。 + +除了存储和计算隔离,不同的计算资源也被隔离,避免了因数据写入、实时查询以及数据压缩或降采样等任务产生的资源竞争, +从而实现高效率的大规模实时分析。 + +数据可以在多个应用程序之间共享而无需争用同一资源池, +这不仅大大提高了效率, +还可以根据需求提供无限的可扩展性。 + +### 灵活的架构支持多种部署策略 + +![GreptimeDB 的架构](/architecture-2.png) + +通过灵活的架构设计原则,不同的模块和组件可以通过模块化和分层设计独立切换、组合或分离。 +例如,我们可以将 Frontend、Datanode 和 Metasrc 模块合并为一个独立的二进制文件,也可以为每个表独立启用或禁用 WAL。 + +灵活的架构允许 GreptimeDB 满足从边缘到云的各种场景中的部署和使用需求,同时仍然使用同一套 API 和控制面板。 +通过良好抽象的分层和封装隔离,GreptimeDB 的部署形式支持从嵌入式、独立、传统集群到云原生的各种环境。 + +## 优异的成本效益 + +GreptimeDB 利用流行的对象存储解决方案来存储大量的时序数据,例如 AWS S3 和 Azure Blob Storage,允许开发者只为使用的存储资源付费。 + +GreptimeDB 使用自适应压缩算法,根据数据的类型和基数来减少数据量,以满足时间和空间复杂性约束。 +例如,对于字符串数据类型,当块的基数超过某个阈值时,GreptimeDB 使用字典压缩; +对于浮点数,GreptimeDB 采用 Chimp 算法,该算法通过分析实际的时间序列数据集来增强 Gorilla(Facebook 的内存 TSDB)的算法, +并提供比传统算法(如 zstd、Snappy 等)更高的压缩率和空间效率。 + +## 高性能 + +在性能优化方面,GreptimeDB 利用 LSM 树、数据分片和基于 Quorum 的 WAL 设计等不同技术来处理大量的时序数据写入时的工作负载。 + +GreptimeDB 的查询引擎强大且快速,得益于矢量化执行和分布式并行处理,并结合了索引功能。 +为了提升数据修剪和过滤效率,GreptimeDB 构建了智能索引和大规模并行处理(MPP)架构。 +该架构使用独立的索引文件记录统计信息,类似于 Apache Parquet 的行组元数据,同时还使用了内置指标记录不同查询的工作负载。 +通过结合基于成本的优化(CBO)和开发者定义的提示,GreptimeDB 能够启发式地构建智能索引,从而进一步提升查询性能。 + +## 易于使用 + +### 易于部署和维护 + +为了简化部署和维护过程,GreptimeDB 提供了 [K8s operator](https://github.com/GreptimeTeam/greptimedb-operator)、[命令行工具](https://github.com/GreptimeTeam/gtctl)、嵌入式[仪表盘](https://github.com/GreptimeTeam/dashboard)和其他有用的工具, +使得开发者可以轻松配置和管理数据库。 +请访问我们官网的 [GreptimeCloud](https://greptime.com) 了解更多信息。 + +### 易于集成 + +GreptimeDB 支持多种数据库连接协议,包括 MySQL、PostgreSQL、InfluxDB、OpenTSDB、Prometheus Remote Storage 和高性能 gRPC。 +此外,还提供了多种编程语言的 SDK,如 Java、Go、Erlang 等。 +我们还在不断与生态系统中的其他开源软件进行集成和连接,以增强开发者体验。 +接下来将详细介绍三种流行的语言:PromQL、SQL 和 Python。 + +PromQL 是一种流行的查询语言, +允许开发者选择和聚合由 Prometheus 提供的实时时序数据。 +它比 SQL 更简单,适用于使用 Grafana 进行可视化和创建告警规则。 +GreptimeDB 原生支持 PromQL,查询引擎会将其转换为查询计划,对其进行优化和执行。 + +SQL 是一种高效的工具, +用于分析跨越较长时间跨度或涉及多个表(如 join)的数据。 +此外,它在数据库管理方面也非常方便。 + +Python 在数据科学家和 AI 专家中非常流行。 +GreptimeDB 允许直接在数据库中运行 Python 脚本。 +开发者可以编写 UDF 和 DataFrame API,通过嵌入 Python 解释器来加速数据处理。 + +### 简单的数据模型与自动创建表 + +结合指标(Tag/Field/Timestamp)模型和关系数据模型(Table), +GreptimeDB 提供了一种称为时序表的新数据模型(见下图),以表格形式呈现数据,由行和列组成,指标的 Tag 和 Value 映射到列,并强制时间索引约束表示时间戳。 + +![时序表](/time-series-table.png) + +然而,我们对 schema 的定义不是强制性的,而是更倾向于 MongoDB 等数据库的无 schema 方法。 +表将在数据写入时动态自动创建,并自动添加新出现的列(Tag 和 Field)。 + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/deployments/authentication/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/deployments/authentication/overview.md new file mode 100644 index 000000000..0fa4148b0 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/deployments/authentication/overview.md @@ -0,0 +1,13 @@ +--- +keywords: [身份验证, 用户 Provider, 静态用户, LDAP 用户, 连接数据库] +description: GreptimeDB 的身份验证概述,介绍了多种用户 Provider 的实现,包括静态用户 Provider 和 LDAP 用户 Provider。 +--- + +# 概述 + +当客户端尝试连接到数据库时,将会进行身份验证。GreptimeDB 通过 “user provider” 进行身份验证。GreptimeDB 中有多种 user +provider 实现: + +- [Static User Provider](./static.md):一个简单的内置 user provider 实现,从静态文件中查找用户。 +- [LDAP User Provider](/enterprise/deployments/authentication.md):**企业版功能**,使用外部 LDAP 服务进行用户身份验证。 + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/user-guide/clients/authentication.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/deployments/authentication/static.md similarity index 55% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7/user-guide/clients/authentication.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/deployments/authentication/static.md index a9b62a790..83d6463c5 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/user-guide/clients/authentication.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/deployments/authentication/static.md @@ -1,6 +1,11 @@ -# 鉴权 +--- +keywords: [静态用户配置, 身份验证, 用户帐户, 配置文件, 固定帐户] +description: 介绍了 GreptimeDB 的静态用户配置,允许通过配置文件设置固定帐户进行身份验证。 +--- -当用户尝试连接到数据库时,将会进行身份验证。 GreptimeDB 提供了简单的内置身份验证机制,允许用户配置一个固定的帐户以方便使用,或者配置一个帐户文件以支持多个用户帐户。通过传入文件,GreptimeDB 会加载其中的所有用户。 +# Static User Provider + +GreptimeDB 提供了简单的内置身份验证机制,允许用户配置一个固定的帐户以方便使用,或者配置一个帐户文件以支持多个用户帐户。通过传入文件,GreptimeDB 会加载其中的所有用户。 GreptimeDB使用`=`作为分隔符,读取文件内每行中的用户和密码。例如: diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/deployments/configuration.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/deployments/configuration.md new file mode 100644 index 000000000..b6cd3f872 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/deployments/configuration.md @@ -0,0 +1,846 @@ +--- +keywords: [配置指南, 命令行选项, 配置文件, 环境变量, 协议选项, 存储选项, WAL 选项, 日志选项] +description: GreptimeDB 的配置指南,介绍了命令行选项、配置文件、环境变量、协议选项、存储选项、WAL 选项、日志选项等详细配置方法。 +--- + +# 配置 GreptimeDB + +GreptimeDB 提供了层次化的配置能力,按照下列优先顺序来生效配置(每个项目都会覆盖下面的项目): + +- Greptime 命令行选项 +- 配置文件选项 +- 环境变量 +- 默认值 + +你只需要设置所需的配置项。 +GreptimeDB 将为未配置的任何设置分配默认值。 + +## 如何设置配置项 + +### Greptime 命令行选项 + +你可以使用命令行参数指定多个配置项。 +例如,以配置的 HTTP 地址启动 GreptimeDB 的独立模式: + +```shell +greptime standalone start --http-addr 127.0.0.1:4000 +``` + +有关 Greptime 命令行支持的所有选项,请参阅 [GreptimeDB 命令行界面](/reference/command-lines.md)。 + +### 配置文件选项 + +你可以在 TOML 文件中指定配置项。 +例如,创建一个名为 `standalone.example.toml` 的配置文件,如下所示: + +```toml +[storage] +type = "File" +data_home = "/tmp/greptimedb/" +``` + +然后使用命令行参数 `-c [file_path]` 指定配置文件。 + +```sh +greptime [standalone | frontend | datanode | metasrv] start -c config/standalone.example.toml +``` + +例如以 standalone 模式启动 GreptimeDB: + +```bash +greptime standalone start -c standalone.example.toml +``` + +#### 示例文件 + +以下是每个 GreptimeDB 组件的示例配置文件,包括所有可用配置项。 +在实际场景中,你只需要配置所需的选项,不需要像示例文件中那样配置所有选项。 + +- [独立模式](https://github.com/GreptimeTeam/greptimedb/blob/VAR::greptimedbVersion/config/standalone.example.toml) +- [前端](https://github.com/GreptimeTeam/greptimedb/blob/VAR::greptimedbVersion/config/frontend.example.toml) +- [数据节点](https://github.com/GreptimeTeam/greptimedb/blob/VAR::greptimedbVersion/config/datanode.example.toml) +- [流节点](https://github.com/GreptimeTeam/greptimedb/blob/VAR::greptimedbVersion/config/flownode.example.toml) +- [元服务](https://github.com/GreptimeTeam/greptimedb/blob/VAR::greptimedbVersion/config/metasrv.example.toml) + +### 环境变量 + +配置文件中的每个项目都可以映射到环境变量。 +例如,使用环境变量设置数据节点的 `data_home` 配置项: + +```toml +# ... +[storage] +data_home = "/data/greptimedb" +# ... +``` + +使用以下 shell 命令以以下格式设置环境变量: + +``` +export GREPTIMEDB_DATANODE__STORAGE__DATA_HOME=/data/greptimedb +``` + +#### 环境变量规则 + +- 每个环境变量应具有组件前缀,例如: + + - `GREPTIMEDB_FRONTEND` + - `GREPTIMEDB_METASRV` + - `GREPTIMEDB_DATANODE` + - `GREPTIMEDB_STANDALONE` + +- 使用**双下划线 `__`**作为分隔符。例如,数据结构 `storage.data_home` 转换为 `STORAGE__DATA_HOME`。 + +环境变量还接受以逗号 `,` 分隔的列表,例如: + +``` +GREPTIMEDB_METASRV__META_CLIENT__METASRV_ADDRS=127.0.0.1:3001,127.0.0.1:3002,127.0.0.1:3003 +``` + +### 协议选项 + +协议选项适用于 `frontend` 和 `standalone` 子命令,它指定了协议服务器地址和其他协议相关的选项。 + +下面的示例配置包含了所有协议选项的默认值。 +你可以在配置文件中更改这些值或禁用某些协议。 +例如禁用 OpenTSDB 协议支持,可以将 `enable` 参数设置为 `false`。 +请注意,为了保障数据库的正常工作,无法禁用 HTTP 和 gRPC 协议。 + +```toml +[http] +addr = "127.0.0.1:4000" +timeout = "30s" +body_limit = "64MB" + +[grpc] +addr = "127.0.0.1:4001" +runtime_size = 8 + +[mysql] +enable = true +addr = "127.0.0.1:4002" +runtime_size = 2 + +[mysql.tls] +mode = "disable" +cert_path = "" +key_path = "" + +[postgres] +enable = true +addr = "127.0.0.1:4003" +runtime_size = 2 + +[postgres.tls] +mode = "disable" +cert_path = "" +key_path = "" + +[opentsdb] +enable = true + +[influxdb] +enable = true + +[prom_store] +enable = true +``` + +下表描述了每个选项的详细信息: + +| 选项 | 键 | 类型 | 描述 | +| ---------- | ------------------ | ------ | ------------------------------------------------------------ | +| http | | | HTTP 服务器选项 | +| | addr | 字符串 | 服务器地址,默认为 "127.0.0.1:4000" | +| | timeout | 字符串 | HTTP 请求超时时间,默认为 "30s" | +| | body_limit | 字符串 | HTTP 最大体积大小,默认为 "64MB" | +| | is_strict_mode | 布尔值 | 是否启用协议的严格校验模式,启用会轻微影响性能,默认为 false | +| grpc | | | gRPC 服务器选项 | +| | addr | 字符串 | 服务器地址,默认为 "127.0.0.1:4001" | +| | runtime_size | 整数 | 服务器工作线程数量,默认为 8 | +| mysql | | | MySQL 服务器选项 | +| | enable | 布尔值 | 是否启用 MySQL 协议,默认为 true | +| | addr | 字符串 | 服务器地址,默认为 "127.0.0.1:4002" | +| | runtime_size | 整数 | 服务器工作线程数量,默认为 2 | +| influxdb | | | InfluxDB 协议选项 | +| | enable | 布尔值 | 是否在 HTTP API 中启用 InfluxDB 协议,默认为 true | +| opentsdb | | | OpenTSDB 协议选项 | +| | enable | 布尔值 | 是否启用 OpenTSDB 协议,默认为 true | +| prom_store | | | Prometheus 远程存储选项 | +| | enable | 布尔值 | 是否在 HTTP API 中启用 Prometheus 远程读写,默认为 true | +| | with_metric_engine | 布尔值 | 是否在 Prometheus 远程写入中使用 Metric Engine,默认为 true | +| postgres | | | PostgresSQL 服务器选项 | +| | enable | 布尔值 | 是否启用 PostgresSQL 协议,默认为 true | +| | addr | 字符串 | 服务器地址,默认为 "127.0.0.1:4003" | +| | runtime_size | 整数 | 服务器工作线程数量,默认为 2 | + +对 MySQL 和 Postgres 接口,我们支持 TLS 配置 + +| Option | Key | Type | Description | +|-------------------------------|-------------|---------|--------------------------------------------------| +| `mysql.tls` 或 `postgres.tls` | | | MySQL 或 Postgres 的 TLS 配置 | +| | `mode` | String | TLS 模式,支持 `disable`, `prefer` and `require` | +| | `cert_path` | String | TLS 证书文件路径 | +| | `key_path` | String | TLS 私钥文件路径 | +| | `watch` | Boolean | 监控文件变化,自动重新加载证书或私钥 | + + +### 存储选项 + +`存储`选项在 `datanode` 和 `standalone` 模式下有效,它指定了数据库数据目录和其他存储相关的选项。 + +GreptimeDB 支持将数据保存在本地文件系统, AWS S3 以及其兼容服务(比如 MinIO、digitalocean space、腾讯 COS、百度对象存储(BOS)等),Azure Blob Storage 和阿里云 OSS。 + +| 选项 | 键 | 类型 | 描述 | +| ------- | ----------------- | ------ | --------------------------------------------------- | +| storage | | | 存储选项 | +| | type | 字符串 | 存储类型,支持 "File","S3" 和 "Oss" 等. | +| File | | | 本地文件存储选项,当 type="File" 时有效 | +| | data_home | 字符串 | 数据库存储根目录,默认为 "/tmp/greptimedb" | +| S3 | | | AWS S3 存储选项,当 type="S3" 时有效 | +| | name | String | 存储提供商名字,默认为 `S3` | +| | bucket | 字符串 | S3 桶名称 | +| | root | 字符串 | S3 桶中的根路径 | +| | endpoint | 字符串 | S3 的 API 端点 | +| | region | 字符串 | S3 区域 | +| | access_key_id | 字符串 | S3 访问密钥 id | +| | secret_access_key | 字符串 | S3 秘密访问密钥 | +| Oss | | | 阿里云 OSS 存储选项,当 type="Oss" 时有效 | +| | name | String | 存储提供商名字,默认为 `Oss` | +| | bucket | 字符串 | OSS 桶名称 | +| | root | 字符串 | OSS 桶中的根路径 | +| | endpoint | 字符串 | OSS 的 API 端点 | +| | access_key_id | 字符串 | OSS 访问密钥 id | +| | secret_access_key | 字符串 | OSS 秘密访问密钥 | +| Azblob | | | Azure Blob 存储选项,当 type="Azblob" 时有效 | +| | name | String | 存储提供商名字,默认为 `Azblob` | +| | container | 字符串 | 容器名称 | +| | root | 字符串 | 容器中的根路径 | +| | endpoint | 字符串 | Azure Blob 存储的 API 端点 | +| | account_name | 字符串 | Azure Blob 存储的账户名 | +| | account_key | 字符串 | 访问密钥 | +| | sas_token | 字符串 | 共享访问签名 | +| Gsc | | | Google Cloud Storage 存储选项,当 type="Gsc" 时有效 | +| | name | String | 存储提供商名字,默认为 `Gsc` | +| | root | 字符串 | Gsc 桶中的根路径 | +| | bucket | 字符串 | Gsc 桶名称 | +| | scope | 字符串 | Gsc 权限 | +| | credential_path | 字符串 | Gsc 访问证书 | +| | endpoint | 字符串 | GSC 的 API 端点 | + +文件存储配置范例: + +```toml +[storage] +type = "File" +data_home = "/tmp/greptimedb/" +``` + +s3 配置范例: + +```toml +[storage] +type = "S3" +bucket = "test_greptimedb" +root = "/greptimedb" +access_key_id = "" +secret_access_key = "" +``` + +### 存储服务的 http 客户端 + +`[storage.http_client]` 设置了向存储服务发送请求的 http 客户端的各种配置。 + +仅当存储服务类型是 “S3”,“Oss”,“Azblob” 或 “Gcs” 时生效。 + +| Key | 类型 | 默认值 | 含义 | +|--------------------------|-----|------------|-------------------------------------------------------------| +| `pool_max_idle_per_host` | 数字 | 1024 | http 连接池中对每个 host 的最大空闲连接数。 | +| `connect_timeout` | 字符串 | “30s”(30秒) | http 客户端在进行连接时的超时 | +| `timeout` | 字符串 | “30s”(30秒) | 总的 http 请求超时,包括了从建立连接到接收完返回值为止的时间。也可视为一个请求从开始到结束的一个完整的截止时间。 | +| `pool_idle_timeout` | 字符串 | “90s”(90秒) | 对空闲连接进行保活( "keep-alive" )的超时。 | + +### 存储引擎提供商 + +`[[storage.providers]]` 用来设置存储引擎的提供商列表。基于这个配置,你可以为每张表指定不同的存储引擎,具体请参考 [create table](/reference/sql/create.md#create-table): + +```toml +# Allows using multiple storages +[[storage.providers]] +name = "S3" +type = "S3" +bucket = "test_greptimedb" +root = "/greptimedb" +access_key_id = "" +secret_access_key = "" + +[[storage.providers]] +name = "Gcs" +type = "Gcs" +bucket = "test_greptimedb" +root = "/greptimedb" +credential_path = "" +``` + +所有配置的这些存储引擎提供商的 `name` 都可以在创建表时用作 `storage` 选项。 + +对于同样提供商的存储,比如你希望使用不同 S3 bucket 来作为不同表的存储引擎,你就可以设置不同的 `name`,并在创建表的时候指定 `storage` 选项。 + +### 对象存储缓存 + +在使用 AWS S3、阿里云 OSS 或 Azure Blob Storage 等远程存储服务时,查询过程中获取数据通常会很耗时,尤其在公有云环境。为了解决这个问题,GreptimeDB 提供了本地缓存机制来加速重复数据的访问。 + +从 v0.11 版本开始,GreptimeDB 默认启用远程对象存储的本地文件缓存。读取和写入缓存容量都设置为 `5GiB`。 + + +通常你无需专门配置缓存,除非你需要修改缓存的大小 +```toml +[storage] +type = "S3" +bucket = "test_greptimedb" +root = "/greptimedb" +access_key_id = "" +secret_access_key = "" +cache_capacity = "10GiB" +``` + + +我们建议你不用设置缓存的目录,因为数据库会自动创建该目录。默认的缓存目录位于 `{data_home}` 目录下。 + + +对于 v0.11 之前的版本,你需要通过在存储设置中配置 `cache_path` 来手动启用读取缓存: + +```toml +[storage] +type = "S3" +bucket = "test_greptimedb" +root = "/greptimedb" +access_key_id = "" +secret_access_key = "" +## 启用对象存储缓存 +cache_path = "/var/data/s3_read_cache" +cache_capacity = "5GiB" +``` + +`cache_path` 指定存储缓存文件的本地目录,而 `cache_capacity` 则决定缓存目录中允许的最大文件总大小(以字节为单位)。你可以通过将 `cache_path` 设置为空字符串来禁用读取缓存。 + + +自 `v0.12` 之后,写入缓存不再是实验性的功能。你可以通过修改 mito 的配置调整缓存的大小 + +```toml +[[region_engine]] +[region_engine.mito] + +write_cache_size = "10GiB" +```` + + +对于 v0.11 之前版本的写入缓存,你需要在 `[region_engine.mito]` 部分将 `enable_experimental_write_cache` 设置为 `true` 来启用: + +```toml +[[region_engine]] +[region_engine.mito] + +enable_experimental_write_cache = true +experimental_write_cache_path = "/var/data/s3_write_cache" +experimental_write_cache_size = "5GiB" +``` + +`experimental_write_cache_path` 默认值位于 `{data_home}` 目录下。 +要禁用写入缓存,请将 `enable_experimental_write_cache` 设置为 `false`。 + +更详细的信息请参阅[性能调优技巧](/user-guide/administration/performance-tuning-tips)。 + + +### WAL 选项 + +datanode 和 standalone 在 `[wal]` 部分可以配置 Write-Ahead-Log 的对应参数: + +#### Local WAL + +```toml +[wal] +file_size = "256MB" +purge_threshold = "4GB" +purge_interval = "10m" +read_batch_size = 128 +sync_write = false +``` + +- `dir`: WAL 的日志目录, 当使用文件 `File` 存储的时候, 默认值为`{data_home}/wal` 。当使用对象存储的时候,必须明确指定。 +- `file_size`: 单个日志文件的最大大小,默认为 `256MB`。 +- `purge_threshold` 和 `purge_interval`: 控制清除任务的触发阈值和间隔 +- `sync_write`: 是否在写入每条日志的时候调用 l `fsync` 刷盘。 + +#### Remote WAL + +```toml +[wal] +provider = "kafka" +broker_endpoints = ["127.0.0.1:9092"] +max_batch_bytes = "1MB" +consumer_wait_timeout = "100ms" +backoff_init = "500ms" +backoff_max = "10s" +backoff_base = 2 +backoff_deadline = "5mins" +overwrite_entry_start_id = false +``` + +- `broker_endpoints`:Kafka 端点 +- `max_batch_bytes`:单个 producer batch 的最大值 +- `consumer_wait_timeout`:consumer 的等待超时时间 +- `backoff_init`:backoff 初始延迟 +- `backoff_max`::backoff 最大延迟 +- `backoff_base`::backoff 指数 +- `backoff_deadline`:重试的截止时间 +- `overwrite_entry_start_id`: 该选项确保在 Kafka 消息被误删除时,系统仍然能够成功重放内存表数据,而不会抛出超出范围(out-of-range)的错误。然而,启用此选项可能会导致意外的数据丢失,因为系统会跳过缺失的条目,而不是将其视为严重错误。 + +##### Remote WAL 鉴权 (Optional) + +```toml +[wal.sasl] +type = "SCRAM-SHA-512" +username = "user" +password = "secret" +``` + +Kafka 客户端 SASL 鉴权配置,支持的 SASL 机制 : `PLAIN`, `SCRAM-SHA-256`, `SCRAM-SHA-512`. + +##### Remote WAL TLS (Optional) + +```toml +[wal.tls] +server_ca_cert_path = "/path/to/server_cert" +client_cert_path = "/path/to/client_cert" +client_key_path = "/path/to/key" +``` + +Kafka 客户端 TLS 配置,支持 TLS(使用系统 CA 证书),TLS(使用特定 CA 证书),mTLS。 + +配置示例: + +**TLS (使用系统 CA 证书)** + +```toml +[wal.tls] +``` + +**TLS (使用特定 CA 证书)** + +```toml +[wal.tls] +server_ca_cert_path = "/path/to/server_cert" +``` + +**mTLS** + +```toml +[wal.tls] +server_ca_cert_path = "/path/to/server_cert" +client_cert_path = "/path/to/client_cert" +client_key_path = "/path/to/key" +``` + +### Logging 选项 + +`frontend`、`metasrv`、`datanode` 和 `standalone` 都可以在 `[logging]` 部分配置 log、tracing 相关参数: + +```toml +[logging] +dir = "/tmp/greptimedb/logs" +level = "info" +enable_otlp_tracing = false +otlp_endpoint = "localhost:4317" +append_stdout = true +[logging.tracing_sample_ratio] +default_ratio = 1.0 +``` + +- `dir`: log 输出目录。 +- `level`: log 输出的日志等级,日志等级有 `info`, `debug`, `error`, `warn`,默认等级为 `info`。 +- `enable_otlp_tracing`:是否打开分布式追踪,默认不开启。 +- `otlp_endpoint`:使用基于 gRPC 的 OTLP 协议导出 tracing 的目标端点,默认值为 `localhost:4317`。 +- `append_stdout`:是否将日志打印到 stdout。默认是`true`。 +- `tracing_sample_ratio`:该字段可以配置 tracing 的采样率,如何使用 `tracing_sample_ratio`,请参考 [如何配置 tracing 采样率](/user-guide/administration/monitoring/tracing.md#指南如何配置-tracing-采样率)。 + +如何使用分布式追踪,请参考 [Tracing](/user-guide/administration/monitoring/tracing.md#教程使用-jaeger-追踪-greptimedb-调用链路) + +### Region 引擎选项 + +datanode 和 standalone 在 `[region_engine]` 部分可以配置不同存储引擎的对应参数。目前只可以配置存储引擎 `mito` 的选项。 + +部分常用的选项如下 + +```toml +[[region_engine]] +[region_engine.mito] +num_workers = 8 +manifest_checkpoint_distance = 10 +max_background_jobs = 4 +auto_flush_interval = "1h" +global_write_buffer_size = "1GB" +global_write_buffer_reject_size = "2GB" +sst_meta_cache_size = "128MB" +vector_cache_size = "512MB" +page_cache_size = "512MB" +sst_write_buffer_size = "8MB" +scan_parallelism = 0 + +[region_engine.mito.inverted_index] +create_on_flush = "auto" +create_on_compaction = "auto" +apply_on_query = "auto" +mem_threshold_on_create = "64M" +intermediate_path = "" + +[region_engine.mito.memtable] +type = "time_series" +``` + +此外,`mito` 也提供了一个实验性质的 memtable。该 memtable 主要优化大量时间序列下的写入性能和内存占用。其查询性能可能会不如默认的 `time_series` memtable。 + +```toml +[region_engine.mito.memtable] +type = "partition_tree" +index_max_keys_per_shard = 8192 +data_freeze_threshold = 32768 +fork_dictionary_bytes = "1GiB" +``` + +以下是可供使用的选项 + +| 键 | 类型 | 默认值 | 描述 | +| ---------------------------------------- | ------ | ------------- | ---------------------------------------------------------------------------------------------------------------------- | +| `num_workers` | 整数 | `8` | 写入线程数量 | +| `manifest_checkpoint_distance` | 整数 | `10` | 每写入 `manifest_checkpoint_distance` 个 manifest 文件创建一次 checkpoint | +| `max_background_jobs` | 整数 | `4` | 后台线程数量 | +| `auto_flush_interval` | 字符串 | `1h` | 自动 flush 超过 `auto_flush_interval` 没 flush 的 region | +| `global_write_buffer_size` | 字符串 | `1GB` | 写入缓冲区大小,默认值为内存总量的 1/8,但不会超过 1GB | +| `global_write_buffer_reject_size` | 字符串 | `2GB` | 写入缓冲区内数据的大小超过 `global_write_buffer_reject_size` 后拒绝写入请求,默认为 `global_write_buffer_size` 的 2 倍 | +| `sst_meta_cache_size` | 字符串 | `128MB` | SST 元数据缓存大小。设为 0 可关闭该缓存
默认为内存的 1/32,不超过 128MB | +| `vector_cache_size` | 字符串 | `512MB` | 内存向量和 arrow array 的缓存大小。设为 0 可关闭该缓存
默认为内存的 1/16,不超过 512MB | +| `page_cache_size` | 字符串 | `512MB` | SST 数据页的缓存。设为 0 可关闭该缓存
默认为内存的 1/8 | +| `selector_result_cache_size` | 字符串 | `512MB` | `last_value()` 等时间线检索结果的缓存。设为 0 可关闭该缓存
默认为内存的 1/16,不超过 512MB | +| `sst_write_buffer_size` | 字符串 | `8MB` | SST 的写缓存大小 | +| `scan_parallelism` | 整数 | `0` | 扫描并发度 (默认 1/4 CPU 核数)
- `0`: 使用默认值 (1/4 CPU 核数)
- `1`: 单线程扫描
- `n`: 按并行度 n 扫描 | +| `inverted_index.create_on_flush` | 字符串 | `auto` | 是否在 flush 时构建索引
- `auto`: 自动
- `disable`: 从不 | +| `inverted_index.create_on_compaction` | 字符串 | `auto` | 是否在 compaction 时构建索引
- `auto`: 自动
- `disable`: 从不 | +| `inverted_index.apply_on_query` | 字符串 | `auto` | 是否在查询时使用索引
- `auto`: 自动
- `disable`: 从不 | +| `inverted_index.mem_threshold_on_create` | 字符串 | `64M` | 创建索引时如果超过该内存阈值则改为使用外部排序
设置为空会关闭外排,在内存中完成所有排序 | +| `inverted_index.intermediate_path` | 字符串 | `""` | 存放外排临时文件的路径 (默认 `{data_home}/index_intermediate`). | +| `inverted_index.metadata_cache_size` | 字符串 | `64MiB` | 倒排索引元数据缓存大小 | +| `inverted_index.content_cache_size` | 字符串 | `128MiB` | 倒排索引文件内容缓存大小 | +| `inverted_index.content_cache_page_size` | 字符串 | `64KiB` | 倒排索引文件内容缓存页大小。倒排索引文件内容以页为单位进行读取和缓存,该配置项用于调整读取和缓存的粒度,优化缓存命中率。 | +| `memtable.type` | 字符串 | `time_series` | Memtable type.
- `time_series`: time-series memtable
- `partition_tree`: partition tree memtable (实验性功能) | +| `memtable.index_max_keys_per_shard` | 整数 | `8192` | 一个 shard 内的主键数
只对 `partition_tree` memtable 生效 | +| `memtable.data_freeze_threshold` | 整数 | `32768` | 一个 shard 内写缓存可容纳的最大行数
只对 `partition_tree` memtable 生效 | +| `memtable.fork_dictionary_bytes` | 字符串 | `1GiB` | 主键字典的大小
只对 `partition_tree` memtable 生效 | + +### 设定 meta client + +`meta_client` 选项适用于 `datanode` 和 `frontend` 模块,用于指定 Metasrv 的相关信息。 + +```toml +[meta_client] +metasrv_addrs = ["127.0.0.1:3002"] +timeout = "3s" +connect_timeout = "1s" +ddl_timeout = "10s" +tcp_nodelay = true +``` + +通过 `meta_client` 配置 metasrv 客户端,包括: + +- `metasrv_addrs`, Metasrv 地址列表,对应 Metasrv 启动配置的 server address。 +- `timeout`, 操作超时时长,默认为 3 秒。 +- `connect_timeout`,连接服务器超时时长,默认为 1 秒。 +- `ddl_timeout`, DDL 执行的超时时间,默认 10 秒。 +- `tcp_nodelay`,接受连接时的 `TCP_NODELAY` 选项,默认为 true。 + +### 指标监控选项 + +这些选项用于将系统监控指标保存到 GreptimeDB 本身。 +有关如何使用此功能的说明,请参见 [监控](/user-guide/administration/monitoring/export-metrics.md) 指南。 + +```toml +[export_metrics] +# Whether to enable export_metrics +enable=true +# Export time interval +write_interval = "30s" +``` + +- `enable`: 是否启用导出指标功能,默认为 `false`。 +- `write_interval`: 指标导出时间间隔。 + +#### `self_import` 方法 + +仅 `frontend` 和 `standalone` 支持使用 `self_import` 方法导出指标。 + +```toml +[export_metrics] +# Whether to enable export_metrics +enable=true +# Export time interval +write_interval = "30s" +[export_metrics.self_import] +db = "information_schema" +``` + +- `db`: 默认的数据库为 `information_schema`,你也可以创建另一个数据库来保存系统指标。 + +#### `remote_write` 方法 + +`datanode`、`frontend`、`metasrv` 和 `standalone` 支持使用 `remote_write` 方法导出指标。 +它将指标发送到与 [Prometheus Remote-Write protocol](https://prometheus.io/docs/concepts/remote_write_spec/) 兼容的接受端。 + +```toml +[export_metrics] +# Whether to enable export_metrics +enable=true +# Export time interval +write_interval = "30s" +[export_metrics.remote_write] +# URL specified by Prometheus Remote-Write protocol +url = "http://127.0.0.1:4000/v1/prometheus/write?db=information_schema" +# Some optional HTTP parameters, such as authentication information +headers = { Authorization = "Basic Z3JlcHRpbWVfdXNlcjpncmVwdGltZV9wd2Q=" } +``` + +- `url`: Prometheus Remote-Write 协议指定的 URL。 +- `headers`: 一些可选的 HTTP 参数,比如认证信息。 + +### Mode 选项 + +`mode` 选项在 `datanode`、`frontend` 和 `standalone` 中可用,它指定了组件的运行模式。 + +在分布式 GreptimeDB 的 `datanode` 和 `frontend` 的配置文件中,需要将值设置为 `distributed`: + +```toml +mode = "distributed" +``` + +在 standalone GreptimeDB 的配置文件中,需要将值设置为 `standalone`: + +```toml +mode = "standalone" +``` + +### 心跳配置 +心跳配置在 `frontend` 和 `datanode` 中可用。 +```toml +[heartbeat] +interval = "3s" +retry_interval = "3s" +``` + +| 键 | 类型 | 默认值 | 描述 | +|----------------------------|-----|------|----------------------------------------------------------| +| `heartbeat` | -- | -- | -- | +| `heartbeat.interval` | 字符串 | `3s` | 向 Metasrv 发送心跳信息的时间间隔 | +| `heartbeat.retry_interval` | 字符串 | `3s` | 向 Metasrv 重试建立心跳连接的时间间隔。(注意在 Datanode 的心跳实现中,这个配置是被忽略的,因为 Datanode 必须在保活机制的租约期内通过心跳完成续租,也就是说其 retry 有特殊策略不允许自定义配置。) | + +### 默认时区配置 + +`default_timezone` 选项适用于 `frontend` 模块和 `standalone` 模式,默认值为 `UTC`。 +它指定了与 GreptimeDB 交互时的客户端默认时区。 +如果在客户端中[指定了时区](/user-guide/timezone.md#在客户端中指定时区),此选项将在该客户端会话中被覆盖。 + +```toml +default_timezone = "UTC" +``` + +`default_timezone` 的值可以是任何时区名称,例如 `Europe/Berlin` 或 `Asia/Shanghai`。 +有关客户端时区如何影响数据的写入和查询,请参阅[时区](/user-guide/timezone.md#时区对-sql-语句的影响)文档。 + +### 仅限于 Metasrv 的配置 + +```toml +# 工作主目录。 +data_home = "/tmp/metasrv/" +# metasrv 的绑定地址,默认为 "127.0.0.1:3002"。 +bind_addr = "127.0.0.1:3002" +# frontend 和 datanode 连接到 metasrv 的通信服务器地址,本地默认为 "127.0.0.1:3002"。 +server_addr = "127.0.0.1:3002" +# metasrv 存储端服务器地址,默认为 "127.0.0.1:2379"。 +store_addr = "127.0.0.1:2379" +# Datanode 选择器类型。 +# - "lease_based" (默认值) +# - "load_based" +# 详情请参阅 "https://docs.greptime.com/contributor-guide/meta/selector" +selector = "lease_based" +# 将数据存储在内存中,默认值为 false。 +use_memory_store = false +## 是否启用 region failover。 +## 该功能仅适用于运行在集群模式下的 GreptimeDB,并且 +## - 使用 Remote WAL +## - 使用共享存储(例如 s3)。 +enable_region_failover = false +# metasrv 的数据库类型. +## 可选项: +## - "EtcdStore" (默认值) +## - "MemoryStore" (纯内存存储 - 仅用于测试) +## - "PostgresStore" +backend = "EtcdStore" + +## Procedure 选项 +[procedure] + +## 最大重试次数 +max_retry_times = 12 + +## 程序的初始重试延迟 +retry_delay = "500ms" + +# Failure detector 选项 +[failure_detector] + +## Failure detector 检测阈值 +threshold = 8.0 + +## 心跳间隔的最小标准差,用于计算可接受的变化。 +min_std_deviation = "100ms" + +## 心跳之间可接受的暂停时间长度。 +acceptable_heartbeat_pause = "10000ms" + +## 首次心跳间隔的估计值。 +first_heartbeat_estimate = "1000ms" + +## Datanode 选项。 +[datanode] + +## Datanode 客户端配置。 +[datanode.client] + +## 操作超时时间 +timeout = "10s" + +## 连接服务器超时时间。 +connect_timeout = "10s" + +## 接受连接时的 `TCP_NODELAY` 选项,默认为 true。 +tcp_nodelay = true + +[wal] +# 可用的 WAL 提供者: +# - `raft_engine`(默认):由于 metasrv 目前仅涉及远程 WAL,因此没有 raft-engine WAL 配置。 +# - `kafka`:在 datanode 中使用 kafka WAL 提供者时,metasrv **必须** 配置 kafka WAL 配置。 +provider = "raft_engine" + +# Kafka WAL 配置。 + +## Kafka 集群的代理端点。 +broker_endpoints = ["127.0.0.1:9092"] + +## 自动为 WAL 创建 topics +## 设置为 `true` 则自动为 WAL 创建 topics +## 否则,使用名为 `topic_name_prefix_[0..num_topics)` 的 topics +auto_create_topics = true + +## Topic 数量。 +num_topics = 64 + +## Topic selector 类型。 +## 可用的 selector 类型: +## - `round_robin`(默认) +selector_type = "round_robin" + +## Kafka topic 通过连接 `topic_name_prefix` 和 `topic_id` 构建。 +topic_name_prefix = "greptimedb_wal_topic" + +## 每个分区的预期副本数。 +replication_factor = 1 + +## 超过此时间创建 topic 的操作将被取消。 +create_topic_timeout = "30s" + +## Kafka 客户端的 backoff 初始时间。 +backoff_init = "500ms" + +## Kafka 客户端的 backoff 最大时间。 +backoff_max = "10s" + +## backoff 指数,即下一个 backoff 时间 = 该指数 * 当前 backoff 时间。 +backoff_base = 2 + +## 如果总等待时间达到截止时间,则停止重新连接。如果此配置缺失,则重新连接不会终止。 +backoff_deadline = "5mins" +``` + +| 键 | 类型 | 默认值 | 描述 | +| --------------------------------------------- | ------- | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | +| `data_home` | String | `/tmp/metasrv/` | 工作目录。 | +| `bind_addr` | String | `127.0.0.1:3002` | Metasrv 的绑定地址。 | +| `server_addr` | String | `127.0.0.1:3002` | 前端和 datanode 连接到 Metasrv 的通信服务器地址,默认为本地主机的 `127.0.0.1:3002`。 | +| `store_addrs` | Array | `["127.0.0.1:2379"]` | 元数据服务地址,默认值为 `["127.0.0.1:2379"]`。支持配置多个服务地址,格式为 `["ip1:port1","ip2:port2",...]`。默认使用 Etcd 做为元数据后端。 | +| `selector` | String | `lease_based` | 创建新表时选择 datanode 的负载均衡策略,详见 [选择器](/contributor-guide/metasrv/selector.md)。 | +| `use_memory_store` | Boolean | `false` | 仅用于在没有 etcd 集群时的测试,将数据存储在内存中,默认值为 `false`。 | +| enable_region_failover | Bool | false | 是否启用 region failover。
该功能仅在以集群模式运行的 GreptimeDB 上可用,并且
- 使用远程 WAL
- 使用共享存储(如 s3)。 | +| `procedure` | -- | -- | | +| `procedure.max_retry_times` | 整数 | `12` | Procedure 的最大重试次数。 | +| `procedure.retry_delay` | 字符串 | `500ms` | Procedure 初始重试延迟,延迟会指数增长。 | +| `failure_detector` | -- | -- | 故障检测选项。 | +| `failure_detector.threshold` | 浮点数 | `8.0` | Failure detector 用来判断故障条件的阈值。 | +| `failure_detector.min_std_deviation` | 字符串 | `100ms` | 心跳间隔的最小标准差,用于计算可接受的变动范围。 | +| `failure_detector.acceptable_heartbeat_pause` | 字符串 | `10000ms` | 允许的最大心跳暂停时间,用于确定心跳间隔是否可接受。 | +| `failure_detector.first_heartbeat_estimate` | 字符串 | `1000ms` | 初始心跳间隔估算值。 | +| `datanode` | -- | -- | | +| `datanode.client` | -- | -- | Datanode 客户端选项。 | +| `datanode.client.timeout` | 字符串 | `10s` | 操作超时。 | +| `datanode.client.connect_timeout` | 字符串 | `10s` | 连接服务器超时。 | +| `datanode.client.tcp_nodelay` | 布尔值 | `true` | 接受连接的 `TCP_NODELAY` 选项。 | +| wal | -- | -- | -- | +| wal.provider | String | raft_engine | -- | +| wal.broker_endpoints | Array | -- | Kafka 集群的端点 | +| `wal.auto_create_topics` | Bool | `true` | 自动为 WAL 创建 topics
设置为 `true` 则自动为 WAL 创建 topics
否则,使用名为 `topic_name_prefix_[0..num_topics)` 的 topics | +| `wal.num_topics` | Integer | `64` | Topic 数量 | +| wal.selector_type | String | round_robin | topic selector 类型
可用 selector 类型:
- round_robin(默认) | +| wal.topic_name_prefix | String | greptimedb_wal_topic | 一个 Kafka topic 是通过连接 topic_name_prefix 和 topic_id 构建的 | +| wal.replication_factor | Integer | 1 | 每个分区的副本数 | +| wal.create_topic_timeout | String | 30s | 超过该时间后,topic 创建操作将被取消 | +| wal.backoff_init | String | 500ms | Kafka 客户端的 backoff 初始时间 | +| wal.backoff_max | String | 10s | Kafka 客户端的 backoff 最大时间 | +| wal.backoff_base | Integer | 2 | backoff 指数,即下一个 backoff 时间 = 该指数 \* 当前 backoff 时间 | +| wal.backoff_deadline | String | 5mins | 如果总等待时间达到截止时间,则停止重新连接。如果此配置缺失,则重新连接不会终止 | +| `wal.sasl` | String | -- | Kafka 客户端 SASL 配置 | +| `wal.sasl.type` | String | -- | SASL 机制, 可选值: `PLAIN`, `SCRAM-SHA-256`, `SCRAM-SHA-512` | +| `wal.sasl.username` | String | -- | SASL 鉴权用户名 | +| `wal.sasl.password` | String | -- | SASL 鉴权密码 | +| `wal.tls` | String | -- | Kafka 客户端 TLS 配置 | +| `wal.tls.server_ca_cert_path` | String | -- | 服务器 CA 证书地址 | +| `wal.tls.client_cert_path` | String | -- | 客户端证书地址(用于启用 mTLS) | +| `wal.tls.client_key_path` | String | -- | 客户端密钥地址(用于启用 mTLS) | + +### 仅限于 `Datanode` 的配置 + +```toml +node_id = 42 +rpc_hostname = "127.0.0.1" +rpc_addr = "127.0.0.1:3001" +rpc_runtime_size = 8 +``` + +| Key | Type | Description | +| ---------------- | ------ | ------------------------------------------- | +| node_id | 整数 | 该 `datanode` 的唯一标识符。 | +| rpc_hostname | 字符串 | 该 `datanode` 的 Hostname。 | +| rpc_addr | 字符串 | gRPC 服务端地址,默认为`"127.0.0.1:3001"`。 | +| rpc_runtime_size | 整数 | gRPC 服务器工作线程数,默认为 8。 | + +### 仅限于 `Frontend` 的配置 + +```toml +[datanode] +[datanode.client] +connect_timeout = "1s" +tcp_nodelay = true +``` + +| Key | Type | Default | Description | +|-----------------------------------|------|---------|-------------------------| +| `datanode` | -- | -- | | +| `datanode.client` | -- | -- | Datanode 客户端选项。 | +| `datanode.client.connect_timeout` | 字符串 | `1s` | 连接服务器超时。 | +| `datanode.client.tcp_nodelay` | 布尔值 | `true` | 接受连接的 `TCP_NODELAY` 选项。 | diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/deployments/deploy-on-kubernetes/common-helm-chart-configurations.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/deployments/deploy-on-kubernetes/common-helm-chart-configurations.md new file mode 100644 index 000000000..9656601b6 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/deployments/deploy-on-kubernetes/common-helm-chart-configurations.md @@ -0,0 +1,313 @@ +--- +keywords: [Kubernetes, 部署, Helm Chart, 配置] +description: 常见 Helm Chart 配置项 +--- + +# 常见 Helm Chart 配置项 + +对于每一个 Helm Chart,你都可以通过创建 `values.yaml` 来进行配置。当你需要应用配置时,你可以通过 `helm upgrade` 命令来应用配置: + +``` +helm upgrade --install ${release-name} ${chart-name} --namespace ${namespace} -f values.yaml +``` + +## GreptimeDB Cluster Chart + +完整的配置项可参考 [GreptimeDB Cluster Chart](https://github.com/GreptimeTeam/helm-charts/tree/main/charts/greptimedb-cluster/README.md)。 + +### GreptimeDB 运行镜像配置 + +顶层变量 `image` 用于配置集群全局的运行镜像,如下所示: + +```yaml +image: + # -- The image registry + registry: greptime-registry.cn-hangzhou.cr.aliyuncs.com + # -- The image repository + repository: greptime/greptimedb + # -- The image tag + tag: "v0.11.0" + # -- The image pull secrets + pullSecrets: [] +``` + +如果你想为集群中的每个 Role 配置不同的镜像,可以使用 `${role}.podTemplate.main.image` 字段(其中 `role` 可以是 `meta`、`frontend`、`datanode` 和 `flownode`),该字段会**覆盖顶层**变量 `image` 的配置,如下所示: + +```yaml +image: + # -- The image registry + registry: greptime-registry.cn-hangzhou.cr.aliyuncs.com + # -- The image repository + repository: greptime/greptimedb + # -- The image tag + tag: "v0.11.0" + # -- The image pull secrets + pullSecrets: [] + +frontend: + podTemplate: + main: + image: "greptime-registry.cn-hangzhou.cr.aliyuncs.com/greptime/greptimedb:latest" +``` + +此时 `frontend` 的镜像将会被设置为 `greptime-registry.cn-hangzhou.cr.aliyuncs.com/greptime/greptimedb:latest`,而其他组件的镜像将会使用顶层变量 `image` 的配置。 + +### 服务端口配置 + +你可以使用如下字段来配置服务端口,如下所示: + +- `httpServicePort`: 用于配置 HTTP 服务的端口,默认 4000; +- `grpcServicePort`: 用于配置 SQL 服务的端口,默认 4001; +- `mysqlServicePort`: 用于配置 MySQL 服务的端口,默认 4002; +- `postgresServicePort`: 用于配置 PostgreSQL 服务的端口,默认 4003; + +### Datanode 存储配置 + +你可以通过 `datanode.storage` 字段来配置 Datanode 的存储,如下所示: + +```yaml +datanode: + storage: + # -- Storage class for datanode persistent volume + storageClassName: null + # -- Storage size for datanode persistent volume + storageSize: 10Gi + # -- Storage retain policy for datanode persistent volume + storageRetainPolicy: Retain + # -- The dataHome directory, default is "/data/greptimedb/" + dataHome: "/data/greptimedb" +``` + +- `storageClassName`: 用于配置 StorageClass,默认使用 Kubernetes 当前默认的 StorageClass; +- `storageSize`: 用于配置 Storage 的大小,默认 10Gi。你可以使用常用的容量单位,如 `10Gi`、`10GB` 等; +- `storageRetainPolicy`: 用于配置 Storage 的保留策略,默认 `Retain`,如果设置为 `Delete`,则当集群被删除时,相应的 Storage 也会被删除; +- `dataHome`: 用于配置数据目录,默认 `/data/greptimedb/`; + +### 运行资源配置 + +顶层变量 `base.podTemplate.main.resources` 用于全局配置每个 Role 的资源,如下所示: + +```yaml +base: + podTemplate: + main: + resources: + requests: + memory: "1Gi" + cpu: "1" + limits: + memory: "2Gi" + cpu: "2" +``` + +如果你想为集群中的每个 Role 配置不同的资源,可以使用 `${role}.podTemplate.main.resources` 字段(其中 `role` 可以是 `meta`、`frontend`、`datanode` 等),改字段会**覆盖顶层**变量 `base.podTemplate.main.resources` 的配置,如下所示: + +```yaml +base: + podTemplate: + main: + resources: + requests: + memory: "1Gi" + cpu: "1" + limits: + memory: "2Gi" + cpu: "2" + +frontend: + podTemplate: + main: + resources: + requests: + cpu: "2" + memory: "4Gi" + limits: + cpu: "4" + memory: "8Gi" +``` + +### 服务运行副本数配置 + +对于不同 Role 的副本数,可以通过 `${role}.replicas` 字段进行配置对应的副本数,如下所示: + +```yaml +frontend: + replicas: 3 + +datanode: + replicas: 3 +``` + +你可以通过配置其副本数来实现水平扩缩。 + +### 环境变量配置 + +你既可以通过 `base.podTemplate.main.env` 字段配置全局的环境变量,也可以通过 `${role}.podTemplate.main.env` 字段为每个 Role 配置不同的环境变量,如下所示: + +```yaml +base: + podTemplate: + main: + env: + - name: GLOBAL_ENV + value: "global_value" + +frontend: + podTemplate: + main: + env: + - name: FRONTEND_ENV + value: "frontend_value" +``` + +### 注入配置文件 + +对于不同 Role 的服务,你可以通过 `${role}.configData` 字段注入自定义的 TOML 配置文件,如下所示: + +```yaml +frontend: + configData: | + [[region_engine]] + [region_engine.mito] + # Number of region workers + num_workers = 8 +``` + +你可以通过 [config.md](https://github.com/GreptimeTeam/greptimedb/blob/main/config/config.md) 了解 GreptimeDB 的配置项。 + +除了使用 `${role}.configData` 字段注入配置文件,你还可以通过 `${role}.configFile` 来指定相应的文件,如下所示: + +```yaml +frontend: + configFile: "configs/frontend.toml" +``` + +此时需要确保对应的配置文件路径与执行 `helm upgrade` 命令时所处的目录一致。 + +:::note +用户注入的配置文件默认优先级低于由 GreptimeDB Operator 所接管的配置项,某些配置项仅能通过 GreptimeDB Operator 进行配置,而这些配置项默认会暴露在 `values.yaml` 中。 + +如下默认配置将由 GreptimeDB Operator 管理: + +- Logging 配置; +- Datanode 的 Node ID; +::: + +### 鉴权配置 + +Helm Chart 默认不启用 User Provider 模式的鉴权,你可以通过 `auth.enabled` 字段启用 User Provider 模式的鉴权并配置相应的用户信息,如下所示: + +```yaml +auth: + enabled: true + users: + - name: admin + password: "admin" +``` + +### 日志配置 + +顶层变量 `logging` 用于配置全局日志级别,如下所示: + +```yaml +# -- Global logging configuration +logging: + # -- The log level for greptimedb, only support "debug", "info", "warn", "debug" + level: "info" + + # -- The log format for greptimedb, only support "json" and "text" + format: "text" + + # -- The logs directory for greptimedb + logsDir: "/data/greptimedb/logs" + + # -- Whether to log to stdout only + onlyLogToStdout: false + + # -- indicates whether to persist the log with the datanode data storage. It **ONLY** works for the datanode component. + persistentWithData: false + + # -- The log filters, use the syntax of `target[span\{field=value\}]=level` to filter the logs. + filters: [] + + # -- The slow query log configuration. + slowQuery: + # -- Enable slow query log. + enabled: false + + # -- The threshold of slow query log in seconds. + threshold: "10s" + + # -- Sample ratio of slow query log. + sampleRatio: "1.0" +``` + +其中: + +- `logging.level`: 用于配置全局日志级别,支持 `debug`、`info`、`warn`、`error` 四个级别; +- `logging.format`: 用于配置全局日志格式,支持 `json` 和 `text` 两种格式; +- `logging.logsDir`: 用于配置全局日志目录,默认位于 `/data/greptimedb/logs`; +- `logging.onlyLogToStdout`: 用于配置是否仅输出到标准输出,默认不启用; +- `logging.persistentWithData`: 用于配置是否将日志持久化到数据存储,仅适用于 `datanode` 组件,默认不启用; +- `logging.filters`: 用于配置全局日志过滤器,支持 `target[span\{field=value\}]=level` 的语法,特步地,如果你希望对某些组件启动 `debug` 级别的日志,可以配置如下: + + ```yaml + logging: + level: "info" + format: "json" + filters: + - mito2=debug + ``` + +你还可以通过 `logging.slowQuery` 字段配置来启用慢查询日志,如下所示: + +```yaml +logging: + slowQuery: + enabled: true + threshold: "100ms" + sampleRatio: "1.0" +``` + +其中: + +- `logging.slowQuery.enabled`: 用于配置是否启用慢查询日志,默认不启用; +- `logging.slowQuery.threshold`: 用于配置慢查询日志的阈值; +- `logging.slowQuery.sampleRatio`: 用于配置慢查询日志的采样率,默认 1.0(即全部采样); + +如果配置了输出目录 `logging.logsDir`,则慢查询日志会输出到该目录下。 + +每一个 Role 的日志配置都可以通过 `${role}.logging` 字段进行配置,其字段与顶层 `logging` 一致,并会**覆盖**顶层变量 `logging` 的配置,比如: + +```yaml +frontend: + logging: + level: "debug" +``` + +### 启用 Flownode + +Helm Chart 默认不启用 Flownode,你可以通过 `flownode.enabled` 字段启用 Flownode,如下所示: + +```yaml +flownode: + enabled: true +``` + +`flownode` 的其他字段的配置与其他 Role 的配置一致,比如: + +```yaml +flownode: + enabled: false + replicas: 1 + podTemplate: + main: + resources: + requests: + memory: "1Gi" + cpu: "1" + limits: + memory: "2Gi" + cpu: "2" +``` + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/deployments/deploy-on-kubernetes/getting-started.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/deployments/deploy-on-kubernetes/getting-started.md new file mode 100644 index 000000000..fda7c451b --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/deployments/deploy-on-kubernetes/getting-started.md @@ -0,0 +1,556 @@ +--- +keywords: [Kubernetes 部署, GreptimeDB Operator, 测试集群, 安装, 验证, etcd 集群, 监控集成] +description: 在 Kubernetes 上使用 GreptimeDB Operator 部署 GreptimeDB 集群的指南,包括前置条件、创建测试集群、安装和验证步骤。 +--- + +# 立即开始 + +在该指南中,你将学会如何使用 GreptimeDB Operator 在 Kubernetes 上部署 GreptimeDB 集群。 + +:::note +以下输出可能会因 Helm chart 版本和具体环境的不同而有细微差别。 +::: + +## 前置条件 + +- [Docker](https://docs.docker.com/get-started/get-docker/) >= v23.0.0 +- [kubectl](https://kubernetes.io/docs/tasks/tools/install-kubectl/) >= v1.18.0 +- [Helm](https://helm.sh/docs/intro/install/) >= v3.0.0 +- [kind](https://kind.sigs.k8s.io/docs/user/quick-start/) >= v0.20.0 + +## 创建一个测试 Kubernetes 集群 + +:::warning +不建议在生产环境或性能测试中使用 `kind`。如有这类需求建议使用公有云托管的 Kubernetes 服务,如 [Amazon EKS](https://aws.amazon.com/eks/)、[Google GKE](https://cloud.google.com/kubernetes-engine/) 或 [Azure AKS](https://azure.microsoft.com/en-us/services/kubernetes-service/),或者自行搭建生产级 Kubernetes 集群。 +::: + +目前有很多方法可以创建一个用于测试的 Kubernetes 集群。在本指南中,我们将使用 [kind](https://kind.sigs.k8s.io/docs/user/quick-start/) 来创建一个本地 Kubernetes 集群。如果你想使用已有的 Kubernetes 集群,可以跳过这一步。 + +这里是一个使用 `kind` v0.20.0 的示例: + +```bash +kind create cluster +``` + +
+ 预期输出 +```bash +Creating cluster "kind" ... + ✓ Ensuring node image (kindest/node:v1.27.3) 🖼 + ✓ Preparing nodes 📦 + ✓ Writing configuration 📜 + ✓ Starting control-plane 🕹️ + ✓ Installing CNI 🔌 + ✓ Installing StorageClass 💾 +Set kubectl context to "kind-kind" +You can now use your cluster with: + +kubectl cluster-info --context kind-kind + +Thanks for using kind! 😊 +``` +
+ +使用以下命令检查集群的状态: + +```bash +kubectl cluster-info +``` + +
+ 预期输出 +```bash +Kubernetes control plane is running at https://127.0.0.1:60495 +CoreDNS is running at https://127.0.0.1:60495/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy + +To further debug and diagnose cluster problems, use 'kubectl cluster-info dump'. +``` +
+ +:::note +中国大陆用户如有网络访问问题,可使用 Greptime 提供的位于阿里云镜像仓库的 `kindest/node:v1.27.3` 镜像: + +```bash +kind create cluster --image greptime-registry.cn-hangzhou.cr.aliyuncs.com/kindest/node:v1.27.3 +``` +::: + +## 添加 Greptime Helm 仓库 + +:::note +中国大陆用户如有网络访问问题,可跳过这一步骤并直接参考下一步中使用阿里云 OCI 镜像仓库的方式。采用这一方式将无需手动添加 Helm 仓库。 +::: + +我们提供了 GreptimeDB Operator 和 GreptimeDB 集群的[官方 Helm 仓库](https://github.com/GreptimeTeam/helm-charts)。你可以通过运行以下命令来添加仓库: + +```bash +helm repo add greptime https://greptimeteam.github.io/helm-charts/ +helm repo update +``` + +检查 Greptime Helm 仓库中的 charts: + +```bash +helm search repo greptime +``` + +
+ 预期输出 +```bash +NAME CHART VERSION APP VERSION DESCRIPTION +greptime/greptimedb-cluster 0.2.25 0.9.5 A Helm chart for deploying GreptimeDB cluster i... +greptime/greptimedb-operator 0.2.9 0.1.3-alpha.1 The greptimedb-operator Helm chart for Kubernetes. +greptime/greptimedb-standalone 0.1.27 0.9.5 A Helm chart for deploying standalone greptimedb +``` +
+ +## 安装和验证 GreptimeDB Operator + +现在我们准备使用 Helm 在 Kubernetes 集群上安装 GreptimeDB Operator。 + +### 安装 GreptimeDB Operator + +[GreptimeDB Operator](https://github.com/GrepTimeTeam/greptimedb-operator) 是一个用于管理 GreptimeDB 集群生命周期的 Kubernetes operator。 + +让我们在 `greptimedb-admin` 命名空间中安装最新版本的 GreptimeDB Operator: + +```bash +helm install greptimedb-operator greptime/greptimedb-operator -n greptimedb-admin --create-namespace +``` + +
+ 预期输出 +```bash +NAME: greptimedb-operator +LAST DEPLOYED: Tue Oct 29 18:40:10 2024 +NAMESPACE: greptimedb-admin +STATUS: deployed +REVISION: 1 +TEST SUITE: None +NOTES: +*********************************************************************** + Welcome to use greptimedb-operator + Chart version: 0.2.9 + GreptimeDB Operator version: 0.1.3-alpha.1 +*********************************************************************** + +Installed components: +* greptimedb-operator + +The greptimedb-operator is starting, use `kubectl get deployments greptimedb-operator -n greptimedb-admin` to check its status. +``` +
+ +:::note +中国大陆用户如有网络访问问题,可直接使用阿里云 OCI 镜像仓库的方式安装 GreptimeDB Operator: + +```bash +helm install greptimedb-operator \ + oci://greptime-registry.cn-hangzhou.cr.aliyuncs.com/charts/greptimedb-operator \ + --set image.registry=greptime-registry.cn-hangzhou.cr.aliyuncs.com \ + -n greptimedb-admin \ + --create-namespace +``` + +此时我们也将镜像仓库设置为 Greptime 官方的阿里云镜像仓库。 +::: + +:::note +我们还可以直接使用 `kubectl` 和 `bundle.yaml` 来安装最新版本的 GreptimeDB Operator: + +```bash +kubectl apply -f \ + https://github.com/GreptimeTeam/greptimedb-operator/releases/latest/download/bundle.yaml \ + --server-side +``` + +这种方式仅适用于在测试环境快速部署 GreptimeDB Operator,不建议在生产环境中使用。 +::: + +### 验证 GreptimeDB Operator 安装 + +检查 GreptimeDB Operator 的状态: + +```bash +kubectl get pods -n greptimedb-admin -l app.kubernetes.io/instance=greptimedb-operator +``` + +
+ 预期输出 +```bash +NAME READY STATUS RESTARTS AGE +greptimedb-operator-68d684c6cf-qr4q4 1/1 Running 0 4m8s +``` +
+ +你也可以检查 CRD 的安装: + +```bash +kubectl get crds | grep greptime +``` + +
+ 预期输出 +```bash +greptimedbclusters.greptime.io 2024-10-28T08:46:27Z +greptimedbstandalones.greptime.io 2024-10-28T08:46:27Z +``` +
+ +GreptimeDB Operator 将会使用 `greptimedbclusters.greptime.io` and `greptimedbstandalones.greptime.io` 这两个 CRD 来管理 GreptimeDB 集群和单机实例。 + +## 安装 etcd 集群 + +GreptimeDB 集群需要一个 etcd 集群来存储元数据。让我们使用 Bitnami 的 etcd Helm [chart](https://hub.docker.com/r/bitnami/etcd) 来安装一个 etcd 集群。 + +```bash +helm install etcd \ + oci://registry-1.docker.io/bitnamicharts/etcd \ + --version 10.2.12 \ + --set replicaCount=3 \ + --set auth.rbac.create=false \ + --set auth.rbac.token.enabled=false \ + --create-namespace \ + -n etcd-cluster +``` + +
+ 预期输出 +```bash +NAME: etcd +LAST DEPLOYED: Mon Oct 28 17:01:38 2024 +NAMESPACE: etcd-cluster +STATUS: deployed +REVISION: 1 +TEST SUITE: None +NOTES: +CHART NAME: etcd +CHART VERSION: 10.2.12 +APP VERSION: 3.5.15 + +** Please be patient while the chart is being deployed ** + +etcd can be accessed via port 2379 on the following DNS name from within your cluster: + + etcd.etcd-cluster.svc.cluster.local + +To create a pod that you can use as a etcd client run the following command: + + kubectl run etcd-client --restart='Never' --image docker.io/bitnami/etcd:3.5.15-debian-12-r6 --env ETCDCTL_ENDPOINTS="etcd.etcd-cluster.svc.cluster.local:2379" --namespace etcd-cluster --command -- sleep infinity + +Then, you can set/get a key using the commands below: + + kubectl exec --namespace etcd-cluster -it etcd-client -- bash + etcdctl put /message Hello + etcdctl get /message + +To connect to your etcd server from outside the cluster execute the following commands: + + kubectl port-forward --namespace etcd-cluster svc/etcd 2379:2379 & + echo "etcd URL: http://127.0.0.1:2379" + +WARNING: There are "resources" sections in the chart not set. Using "resourcesPreset" is not recommended for production. For production installations, please set the following values according to your workload needs: +- disasterRecovery.cronjob.resources +- resources + +info https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/ +``` +
+ +当 etcd 集群准备好后,你可以使用以下命令检查 Pod 的状态: + +```bash +kubectl get pods -n etcd-cluster -l app.kubernetes.io/instance=etcd +``` + +
+ 预期输出 +```bash +NAME READY STATUS RESTARTS AGE +etcd-0 1/1 Running 0 2m8s +etcd-1 1/1 Running 0 2m8s +etcd-2 1/1 Running 0 2m8s +``` +
+ +:::note +中国大陆用户如有网络访问问题,可直接使用阿里云 OCI 镜像仓库的方式安装 etcd 集群: + +```bash +helm install etcd \ + oci://greptime-registry.cn-hangzhou.cr.aliyuncs.com/charts/etcd \ + --set image.registry=greptime-registry.cn-hangzhou.cr.aliyuncs.com \ + --set image.tag=3.5.12 \ + --set replicaCount=3 \ + --set auth.rbac.create=false \ + --set auth.rbac.token.enabled=false \ + --create-namespace \ + -n etcd-cluster +``` +::: + +你可以通过运行以下命令来测试 etcd 集群: + +```bash +kubectl -n etcd-cluster \ + exec etcd-0 -- etcdctl endpoint health \ + --endpoints=http://etcd-0.etcd-headless.etcd-cluster.svc.cluster.local:2379,http://etcd-1.etcd-headless.etcd-cluster.svc.cluster.local:2379,http://etcd-2.etcd-headless.etcd-cluster.svc.cluster.local:2379 +``` + +
+ 预期输出 +```bash +http://etcd-1.etcd-headless.etcd-cluster.svc.cluster.local:2379 is healthy: successfully committed proposal: took = 3.008575ms +http://etcd-0.etcd-headless.etcd-cluster.svc.cluster.local:2379 is healthy: successfully committed proposal: took = 3.136576ms +http://etcd-2.etcd-headless.etcd-cluster.svc.cluster.local:2379 is healthy: successfully committed proposal: took = 3.147702ms +``` +
+ +## 安装带有监控集成的 GreptimeDB 集群 + +目前我们已经准备好了 GreptimeDB Operator 和 etcd 集群,现在我们可以部署一个带监控集成的最小 GreptimeDB 集群: + +:::warning +本文档中的默认配置不适用于生产环境,你应该根据自己的需求调整配置。 +::: + +```bash +helm install mycluster \ + --set monitoring.enabled=true \ + --set grafana.enabled=true \ + greptime/greptimedb-cluster \ + -n default +``` + +:::note +中国大陆用户如有网络访问问题,可直接使用阿里云 OCI 镜像仓库的方式来安装 GreptimeDB 集群: + +```bash +helm install mycluster \ + oci://greptime-registry.cn-hangzhou.cr.aliyuncs.com/charts/greptimedb-cluster \ + --set image.registry=greptime-registry.cn-hangzhou.cr.aliyuncs.com \ + --set initializer.registry=greptime-registry.cn-hangzhou.cr.aliyuncs.com \ + --set grafana.enabled=true \ + --set grafana.image.registry=greptime-registry.cn-hangzhou.cr.aliyuncs.com \ + --set monitoring.enabled=true \ + --set monitoring.vector.registry=greptime-registry.cn-hangzhou.cr.aliyuncs.com \ + -n default +``` + +如果你使用了不同的集群名称和命名空间,请将 `mycluster` 和 `default` 替换为你的配置。 +::: + +
+ 预期输出 +```bash +Release "mycluster" does not exist. Installing it now. +NAME: mycluster +LAST DEPLOYED: Mon Oct 28 17:19:47 2024 +NAMESPACE: default +STATUS: deployed +REVISION: 1 +NOTES: +*********************************************************************** + Welcome to use greptimedb-cluster + Chart version: 0.2.25 + GreptimeDB Cluster version: 0.9.5 +*********************************************************************** + +Installed components: +* greptimedb-frontend +* greptimedb-datanode +* greptimedb-meta + +The greptimedb-cluster is starting, use `kubectl get pods -n default` to check its status. +``` +
+ +当启用 `monitoring` 选项时,我们将会在 cluster 所属的命名空间下部署一个名为 `${cluster}-monitor` 的 GreptimeDB Standalone 实例,用于存储集群的 metrics 和 logs 这类监控数据。同时,我们也会为集群内的每一个 Pod 部署一个 [Vector](https://github.com/vectordotdev/vector) sidecar 来收集集群的 metrics 和 logs,并发送给 GreptimeDB Standalone 实例。 + + +当启用 `grafana` 选项时,我们将会部署一个 Grafana 实例,并配置 [Grafana](https://grafana.com/) 使用 GreptimeDB Standalone 实例作为数据源(分别使用 Prometheus 和 MySQL 协议),从而我们开箱即可使用 Grafana 来可视化 GreptimeDB 集群的监控数据。默认地,Grafana 将会使用 `mycluster` 和 `default` 作为集群名称和命名空间来创建数据源。如果你想要监控具有不同名称或不同命名空间的集群,那就需要基于不同的集群名称和命名空间来创建不同的数据源配置。你可以创建一个如下所示的 `values.yaml` 文件: + +```yaml +grafana: + datasources: + datasources.yaml: + datasources: + - name: greptimedb-metrics + type: prometheus + url: http://${cluster}-monitor-standalone.${namespace}.svc.cluster.local:4000/v1/prometheus + access: proxy + isDefault: true + + - name: greptimedb-logs + type: mysql + url: ${cluster}-monitor-standalone.${namespace}.svc.cluster.local:4002 + access: proxy + database: public +``` + +上述配置将在 Grafana dashboard 中为 GreptimeDB 集群的指标和日志创建默认的数据源: + +- `greptimedb-metrics`:集群的指标存储在独立的监控数据库中,并对外暴露为 Prometheus 协议(`type: prometheus`); + +- `greptimedb-logs`:集群的日志存储在独立的监控数据库中,并对外暴露为 MySQL 协议(`type: mysql`)。默认使用 `public` 数据库; + +然后将上面的 `values.yaml` 中的 `${cluster}` 和 `${namespace}` 替换为你想要的值,并使用以下命令安装 GreptimeDB 集群: + +```bash +helm install ${cluster} \ + --set monitoring.enabled=true \ + --set grafana.enabled=true \ + greptime/greptimedb-cluster \ + -f values.yaml \ + -n ${namespace} +``` + +当启动集群安装之后,我们可以用如下命令检查 GreptimeDB 集群的状态。若你使用了不同的集群名和命名空间,可将 `default` 和 `mycluster` 替换为你的配置: + +```bash +kubectl -n default get greptimedbclusters.greptime.io mycluster +``` + +
+ 预期输出 +```bash +NAME FRONTEND DATANODE META FLOWNODE PHASE VERSION AGE +mycluster 1 1 1 0 Running v0.9.5 5m12s +``` +
+ +上面的命令将会显示 GreptimeDB 集群的状态。当 `PHASE` 为 `Running` 时,表示 GreptimeDB 集群已经成功启动。 + +你还可以检查 GreptimeDB 集群的 Pod 状态: + +```bash +kubectl -n default get pods +``` + +
+ 预期输出 +```bash +NAME READY STATUS RESTARTS AGE +mycluster-datanode-0 2/2 Running 0 77s +mycluster-frontend-6ffdd549b-9s7gx 2/2 Running 0 66s +mycluster-grafana-675b64786-ktqps 1/1 Running 0 6m35s +mycluster-meta-58bc88b597-ppzvj 2/2 Running 0 86s +mycluster-monitor-standalone-0 1/1 Running 0 6m35s +``` +
+ +正如你所看到的,我们默认创建了一个最小的 GreptimeDB 集群,包括 1 个 frontend、1 个 datanode 和 1 个 metasrv。关于一个完整的 GreptimeDB 集群的组成,你可以参考 [architecture](/user-guide/concepts/architecture.md)。除此之外,我们还部署了一个独立的 GreptimeDB Standalone 实例(`mycluster-monitor-standalone-0`)用以存储监控数据和一个 Grafana 实例(`mycluster-grafana-675b64786-ktqps`)用以可视化集群的监控数据。 + +## 探索 GreptimeDB 集群 + +### 访问 GreptimeDB 集群 + +你可以通过使用 `kubectl port-forward` 命令转发 frontend 服务来访问 GreptimeDB 集群: + +```bash +kubectl -n default port-forward svc/mycluster-frontend 4000:4000 4001:4001 4002:4002 4003:4003 +``` + +
+ 预期输出 +```bash +Forwarding from 127.0.0.1:4000 -> 4000 +Forwarding from [::1]:4000 -> 4000 +Forwarding from 127.0.0.1:4001 -> 4001 +Forwarding from [::1]:4001 -> 4001 +Forwarding from 127.0.0.1:4002 -> 4002 +Forwarding from [::1]:4002 -> 4002 +Forwarding from 127.0.0.1:4003 -> 4003 +Forwarding from [::1]:4003 -> 4003 +``` +
+ +请注意,当你使用了其他集群名和命名空间时,你可以使用如下命令,并将 `${cluster}` 和 `${namespace}` 替换为你的配置: + +```bash +kubectl -n ${namespace} port-forward svc/${cluster}-frontend 4000:4000 4001:4001 4002:4002 4003:4003 +``` + +:::warning +如果你想将服务暴露给公网访问,可以使用带有 `--address` 选项的 `kubectl port-forward` 命令: + +```bash +kubectl -n default port-forward --address 0.0.0.0 svc/mycluster-frontend 4000:4000 4001:4001 4002:4002 4003:4003 +``` + +在将服务暴露给公网访问之前,请确保你已经配置了适当的安全设置。 +::: + +打开浏览器并访问 `http://localhost:4000/dashboard` 来访问 [GreptimeDB Dashboard](https://github.com/GrepTimeTeam/dashboard)。 + +如果你想使用其他工具如 `mysql` 或 `psql` 来连接 GreptimeDB 集群,你可以参考 [快速入门](/getting-started/quick-start.md)。 + +### 访问 Grafana dashboard + +你可以使用 `kubectl port-forward` 命令转发 Grafana 服务: + +```bash +kubectl -n default port-forward svc/mycluster-grafana 18080:80 +``` + +请注意,当你使用了其他集群名和命名空间时,你可以使用如下命令,并将 `${cluster}` 和 `${namespace}` 替换为你的配置: + +```bash +kubectl -n ${namespace} port-forward svc/${cluster}-grafana 18080:80 +``` + +接着打开浏览器并访问 `http://localhost:18080` 来访问 Grafana dashboard。默认的用户名和密码是 `admin` 和 `gt-operator`: + +![Grafana Dashboard](/kubernetes-cluster-grafana-dashboard.jpg) + +目前有三个可用的 Dashboard: + +- **GreptimeDB Cluster Metrics**: 用于显示 GreptimeDB 集群的 Metrics; +- **GreptimeDB Cluster Logs**: 用于显示 GreptimeDB 集群的日志; +- **GreptimeDB Cluster Slow Queries**: 用于显示 GreptimeDB 集群的慢查询; + +## 清理 + +:::danger +清理操作将会删除 GreptimeDB 集群的元数据和数据。请确保在继续操作之前已经备份了数据。 +::: + +### 停止端口转发 + +可以使用以下命令停止 GreptimeDB 集群的端口转发: + +```bash +pkill -f kubectl port-forward +``` + +### 卸载 GreptimeDB 集群 + +可以使用以下命令卸载 GreptimeDB 集群: + +```bash +helm -n default uninstall mycluster +``` + +### 删除 PVCs + +为了安全起见,PVCs 默认不会被删除。如果你想删除 PV 数据,你可以使用以下命令: + +```bash +kubectl -n default delete pvc -l app.greptime.io/component=mycluster-datanode +kubectl -n default delete pvc -l app.greptime.io/component=mycluster-monitor-standalone +``` + +### 清理 etcd 数据 + +你可以使用以下命令清理 etcd 集群: + +```bash +kubectl -n etcd-cluster exec etcd-0 -- etcdctl del "" --from-key=true +``` + +### 删除 Kubernetes 集群 + +如果你使用 `kind` 创建 Kubernetes 集群,你可以使用以下命令销毁集群: + +```bash +kind delete cluster +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/deployments/deploy-on-kubernetes/greptimedb-operator-management.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/deployments/deploy-on-kubernetes/greptimedb-operator-management.md new file mode 100644 index 000000000..eb5356a68 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/deployments/deploy-on-kubernetes/greptimedb-operator-management.md @@ -0,0 +1,229 @@ +--- +keywords: [Operator 管理, 安装, 升级, 配置, 卸载, 自动化部署, 多云支持, 扩缩容, 监控] +description: GreptimeDB Operator 的管理指南,包括安装、升级、配置和卸载的详细步骤。 +--- + +# GreptimeDB Operator 的管理 + +GreptimeDB Operator 使用 [Operator 模式](https://kubernetes.io/docs/concepts/extend-kubernetes/operator/) 在 [Kubernetes](https://kubernetes.io/) 上管理 [GreptimeDB](https://github.com/GrepTimeTeam/greptimedb) 资源。 + +就像自动驾驶一样,GreptimeDB Operator 自动化了 GreptimeDB 集群和单机实例的部署、配置和管理。 + +GreptimeDB Operator 包括但不限于以下功能: + +- **自动化部署**: 通过提供 `GreptimeDBCluster` 和 `GreptimeDBStandalone` CRD 来自动化在 Kubernetes 上部署 GreptimeDB 集群和单机实例。 + +- **多云支持**: 用户可以在任何 Kubernetes 集群上部署 GreptimeDB,包括私有环境和公有云环境(如 AWS、GCP、阿里云等)。 + +- **扩缩容**: 通过修改 `GreptimeDBCluster` CR 中的 `replicas` 字段即可轻松实现 GreptimeDB 集群的扩缩容。 + +- **监控**: 通过在 `GreptimeDBCluster` CR 中提供 `monitoring` 字段来自动化部署基于 GreptimeDB 的监控组件。 + +本指南将展示如何在 Kubernetes 上安装、升级、配置和卸载 GreptimeDB Operator。 + +:::note +以下输出可能会因 Helm chart 版本和具体环境的不同而有细微差别。 +::: + +## 前置依赖 + +- Kubernetes >= v1.18.0 +- [kubectl](https://kubernetes.io/docs/tasks/tools/install-kubectl/) >= v1.18.0 +- [Helm](https://helm.sh/docs/intro/install/) >= v3.0.0 + +## 生产环境部署 + +对于生产环境部署,推荐使用 Helm 来安装 GreptimeDB Operator。 + +### 安装 + +你可以参考 [安装和验证 GreptimeDB Operator](/user-guide/deployments/deploy-on-kubernetes/getting-started.md#安装和验证-greptimedb-operator) 获取详细的指导。 + +:::note +如果你使用 [Argo CD](https://argo-cd.readthedocs.io/en/stable/) 来部署应用,请确保 `Application` 已设置 [`ServerSideApply=true`](https://argo-cd.readthedocs.io/en/latest/user-guide/sync-options/#server-side-apply) 以启用 server-side apply(其他 GitOps 工具可能也有类似的设置)。 +::: + +### 升级 + +我们总是将最新版本的 GreptimeDB Operator 作为 Helm chart 发布在我们的[官方 Helm 仓库](https://github.com/GreptimeTeam/helm-charts/tree/main)。 + +当最新版本的 GreptimeDB Operator 发布时,您可以通过运行以下命令来升级 GreptimeDB Operator。 + +#### 更新 Helm 仓库 + +```bash +helm repo update greptime +``` + +
+期望输出 +```bash +Hang tight while we grab the latest from your chart repositories... +...Successfully got an update from the "greptime" chart repository +Update Complete. ⎈Happy Helming!⎈ +``` +
+ +你可以使用以下命令来搜索 GreptimeDB Operator 的最新版本: + +```bash +helm search repo greptime/greptimedb-operator +``` + +
+预期输出 +```bash +NAME CHART VERSION APP VERSION DESCRIPTION +greptime/greptimedb-operator 0.2.9 0.1.3-alpha.1 The greptimedb-operator Helm chart for Kubernetes. +``` +
+ +如果你想列出所有可用的版本,你可以使用以下命令: + +``` +helm search repo greptime/greptimedb-operator --versions +``` + +#### 升级 GreptimeDB Operator + +你可以通过运行以下命令升级到最新发布的 GreptimeDB Operator 版本: + +```bash +helm -n greptimedb-admin upgrade greptimedb-operator greptime/greptimedb-operator +``` + +
+期望输出 +```bash +Release "greptimedb-operator" has been upgraded. Happy Helming! +NAME: greptimedb-operator +LAST DEPLOYED: Mon Oct 28 19:30:52 2024 +NAMESPACE: greptimedb-admin +STATUS: deployed +REVISION: 2 +TEST SUITE: None +NOTES: +*********************************************************************** + Welcome to use greptimedb-operator + Chart version: 0.2.9 + GreptimeDB Operator version: 0.1.3-alpha.1 +*********************************************************************** + +Installed components: +* greptimedb-operator + +The greptimedb-operator is starting, use `kubectl get deployments greptimedb-operator -n greptimedb-admin` to check its status. +``` +
+ +如果你想升级到特定版本,你可以使用以下命令: + +```bash +helm -n greptimedb-admin upgrade greptimedb-operator greptime/greptimedb-operator --version +``` + +升级完成后,你可以使用以下命令来验证安装: + +```bash +helm list -n greptimedb-admin +``` + +
+期望输出 +```bash +NAME NAMESPACE REVISION UPDATED STATUS CHART APP VERSION +greptimedb-operator greptimedb-admin 1 2024-10-30 17:46:45.570975 +0800 CST deployed greptimedb-operator-0.2.9 0.1.3-alpha.1 +``` +
+ +### CRDs + +这里将有两种类型的 CRD 与 GreptimeDB Operator 一起安装:`GreptimeDBCluster` 和 `GreptimeDBStandalone`。 + +你可以使用以下命令来验证安装: + +```bash +kubectl get crd | grep greptime +``` + +
+ 期望输出 +```bash +greptimedbclusters.greptime.io 2024-10-28T08:46:27Z +greptimedbstandalones.greptime.io 2024-10-28T08:46:27Z +``` +
+ +默认情况下,GreptimeDB Operator chart 将管理 CRDs 的安装和升级,用户不需要手动管理它们。如果你想了解这两类 CRD 的具体定义,可参考 GreptimeDB Operator 的 [API 文档](https://github.com/GreptimeTeam/greptimedb-operator/blob/main/docs/api-references/docs.md)。 + +### 配置 + +GreptimeDB Operator chart 提供了一组配置选项,允许您自行配置,您可以参考 [GreptimeDB Operator Helm Chart](https://github.com/GreptimeTeam/helm-charts/blob/main/charts/greptimedb-operator/README.md) 来获取更多详细信息。 + +你可以创建一个 `values.yaml` 来配置 GreptimeDB Operator chart (完整的 `values.yaml` 配置可以参考 [chart](https://github.com/GreptimeTeam/helm-charts/blob/main/charts/greptimedb-operator/values.yaml)),例如: + +```yaml +image: + # -- The image registry + registry: docker.io + # -- The image repository + repository: greptime/greptimedb-operator + # -- The image pull policy for the controller + imagePullPolicy: IfNotPresent + # -- The image tag + tag: latest + # -- The image pull secrets + pullSecrets: [] + +replicas: 1 + +resources: + limits: + cpu: 200m + memory: 256Mi + requests: + cpu: 100m + memory: 128Mi +``` + +:::note +中国大陆用户如有网络访问问题,可将上文中的 `image.registry` 配置为阿里云镜像仓库地址 `greptime-registry.cn-hangzhou.cr.aliyuncs.com`。 +::: + +你可以使用以下命令来安装带有自定义配置的 GreptimeDB Operator: + +```bash +helm -n greptimedb-admin install greptimedb-operator greptime/greptimedb-operator -f values.yaml +``` + +如果你想使用自定义配置升级 GreptimeDB Operator,你可以使用以下命令: + +```bash +helm -n greptimedb-admin upgrade greptimedb-operator greptime/greptimedb-operator -f values.yaml +``` + +你可以使用以下一条同样的命令来安装或升级带有自定义配置的 GreptimeDB Operator: + +```bash +helm -n greptimedb-admin upgrade --install greptimedb-operator greptime/greptimedb-operator -f values.yaml +``` + +### 卸载 + +你可以使用 `helm` 命令来卸载 GreptimeDB Operator: + +```bash +helm -n greptimedb-admin uninstall greptimedb-operator +``` + +默认情况下,卸载 GreptimeDB Operator 时不会删除 CRDs。 + +:::danger +如果你确实想要删除 CRDs,你可以使用以下命令: + +```bash +kubectl delete crd greptimedbclusters.greptime.io greptimedbstandalones.greptime.io +``` + +删除 CRDs 后,相关资源将被删除。 +::: diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/deployments/deploy-on-kubernetes/monitoring/cluster-monitoring-deployment.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/deployments/deploy-on-kubernetes/monitoring/cluster-monitoring-deployment.md new file mode 100644 index 000000000..7922264cd --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/deployments/deploy-on-kubernetes/monitoring/cluster-monitoring-deployment.md @@ -0,0 +1,222 @@ +--- +keywords: [Kubernetes 部署, 集群, 监控] +description: 在 Kubernetes 上部署 GreptimeDB 集群的监控指南,包括自监控和 Prometheus 监控的详细步骤。 +--- + +# 集群监控部署 + +当你使用 GreptimeDB Operator 部署 GreptimeDB 集群后,默认其对应组件(如 Metasrv / Datanode / Frontend)的 HTTP 端口(默认为 `4000`)将会暴露 `/metrics` 端点用于暴露 Prometheus 指标。 + +我们将提供两种方式来监控 GreptimeDB 集群: + +1. **启用 GreptimeDB 自监控**:GreptimeDB Operator 将额外启动一个 GreptimeDB Standalone 实例和 Vector Sidecar 容器,分别用于收集和存储 GreptimeDB 集群的指标和日志数据; +2. **使用 Prometheus Operator 配置 Prometheus 指标监控**:用户需先部署 Prometheus Operator,并创建相应的 Prometheus 实例,然后通过 Prometheus Operator 的 `PodMonitor` 来将 GreptimeDB 集群的 Metrics 数据写入到相应的 Prometheus 中; + +用户可根据自身需求选择合适的监控方式。 + +## 启用 GreptimeDB 自监控 + +自监控模式下 GreptimeDB Operator 将会额外启动一个 GreptimeDB Standalone 实例,用于收集 GreptimeDB 集群的指标和日志数据,其中日志数据将包括集群日志和慢查询日志。为了收集日志数据,GreptimeDB Operator 会在每一个 Pod 中启动一个 [Vector](https://vector.dev/) 的 Sidecar 容器,用于收集 Pod 的日志数据。启用该模式后,集群将自动开启 JSON 格式的日志输出。 + +如果你使用 Helm Chart 部署 GreptimeDB 集群(可参考[立即开始](../getting-started.md)),可对 Helm Chart 的 `values.yaml` 文件进行如下配置: + +```yaml +monitoring: + enabled: true +``` + +此时 Helm Chart 将会部署一个名为 `${cluster}-monitoring` 的 GreptimeDB Standalone 实例,用于收集 GreptimeDB 集群的指标和日志数据,你可以用如下命令进行查看: + +``` +kubectl get greptimedbstandalones.greptime.io ${cluster}-monitoring -n ${namespace} +``` + +默认该 GreptimeDB Standalone 实例会将监控数据使用 Kubernetes 当前默认的 StorageClass 将数据保存于本地存储,你可以根据实际情况进行调整。 + +GreptimeDB Standalone 实例的配置可以通过 Helm Chart 的 `values.yaml` 中的 `monitoring.standalone` 字段进行调整,如下例子所示: + +```yaml +monitoring: + enabled: true + standalone: + base: + main: + # 用于配置 GreptimeDB Standalone 实例的镜像 + image: "greptime-registry.cn-hangzhou.cr.aliyuncs.com/greptime/greptimedb:latest" + + # 用于配置 GreptimeDB Standalone 实例的资源配置 + resources: + requests: + cpu: "2" + memory: "4Gi" + limits: + cpu: "2" + memory: "4Gi" + + # 用于配置 GreptimeDB Standalone 实例的对象存储 + objectStorage: + s3: + # 用于配置 GreptimeDB Standalone 实例的对象存储的 bucket + bucket: "monitoring" + # 用于配置 GreptimeDB Standalone 实例的对象存储的 region + region: "ap-southeast-1" + # 用于配置 GreptimeDB Standalone 实例的对象存储的 secretName + secretName: "s3-credentials" + # 用于配置 GreptimeDB Standalone 实例的对象存储的 root + root: "standalone-with-s3-data" +``` + +GreptimeDB Standalone 实例将会使用 `${cluster}-monitoring-standalone` 作为 Kubernetes Service 的名称来暴露相应的服务,你可以使用如下地址来用于监控数据的读取: + +- **Prometheus 协议的指标监控**:`http://${cluster}-monitor-standalone.${namespace}.svc.cluster.local:4000/v1/prometheus`。 +- **SQL 协议的日志监控**:`${cluster}-monitor-standalone.${namespace}.svc.cluster.local:4002`。默认集群日志会存储于 `public._gt_logs` 表,而将慢查询日志存储于 `public._gt_slow_queries` 表。 + +GreptimeDB 自监控模式将使用 Vector Sidecar 来收集日志数据,你可以通过 `monitoring.vector` 字段来配置 Vector 的配置,如下所示: + +```yaml +monitoring: + enabled: true + vector: + # 用于配置 Vector 的镜像仓库 + registry: greptime-registry.cn-hangzhou.cr.aliyuncs.com + # 用于配置 Vector 的镜像仓库 + repository: timberio/vector + # 用于配置 Vector 的镜像标签 + tag: nightly-alpine + + # 用于配置 Vector 的资源配置 + resources: + requests: + cpu: "50m" + memory: "64Mi" + limits: + cpu: "50m" + memory: "64Mi" +``` + +:::note +如果你没有使用 Helm Chart 进行部署,你也可以通过如下 `GreptimeDBCluster` 的 YAML 来手动配置自监控模式,如下所示: + +```yaml +apiVersion: greptime.io/v1alpha1 +kind: GreptimeDBCluster +metadata: + name: basic +spec: + base: + main: + image: greptime/greptimedb:latest + frontend: + replicas: 1 + meta: + replicas: 1 + etcdEndpoints: + - "etcd.etcd-cluster.svc.cluster.local:2379" + datanode: + replicas: 1 + monitoring: + enabled: true +``` + +其中 `monitoring` 字段用于配置自监控模式,具体可参考 [`GreptimeDBCluster` API 文档](https://github.com/GreptimeTeam/greptimedb-operator/blob/main/docs/api-references/docs.md#monitoringspec)。 +::: + +## 使用 Prometheus Operator 配置 Prometheus 指标监控 + +用户需先部署 Prometheus Operator 并创建相应的 Prometheus 实例,例如可以使用 [kube-prometheus-stack](https://github.com/prometheus-community/helm-charts/tree/main/charts/kube-prometheus-stack) 来部署相应的 Prometheus 技术栈,具体过程可参考其对应的[官方文档](https://github.com/prometheus-community/helm-charts/tree/main/charts/kube-prometheus-stack)。 + +当部署完 Prometheus Operator 和 Prometheus 实例后,用户可通过 Helm Chart 的 `values.yaml` 的 `prometheusMonitor` 字段来配置 Prometheus 监控,如下所示: + +```yaml +prometheusMonitor: + # 用于配置是否启用 Prometheus 监控,此时 GreptimeDB Operator 将会自动创建 Prometheus Operator 的 `PodMonitor` 资源 + enabled: true + # 用于配置 Prometheus 监控的抓取间隔 + interval: "30s" + # 用于配置 Prometheus 监控的标签 + labels: + release: prometheus +``` + +:::note +`labels` 字段需要与相应用于创建 Prometheus 实例的 `matchLabels` 字段保持一致,否则将无法正常抓取到 GreptimeDB 集群的 Metrics 数据。 +::: + +当我们配置完 `prometheusMonitor` 字段后,GreptimeDB Operator 将会自动创建 Prometheus Operator 的 `PodMonitor` 资源,并将 GreptimeDB 集群的 Metrics 数据导入到 Prometheus 中,比如我们可以用如下命令来查看创建的 `PodMonitor` 资源: + +``` +kubectl get podmonitors.monitoring.coreos.com -n ${namespace} +``` + +:::note +如果你没有使用 Helm Chart 进行部署,你也可以通过如下 `GreptimeDBCluster` 的 YAML 来手动配置 Prometheus 监控,如下所示: + +```yaml +apiVersion: greptime.io/v1alpha1 +kind: GreptimeDBCluster +metadata: + name: basic +spec: + base: + main: + image: greptime/greptimedb:latest + frontend: + replicas: 1 + meta: + replicas: 1 + etcdEndpoints: + - "etcd.etcd-cluster.svc.cluster.local:2379" + datanode: + replicas: 1 + prometheusMonitor: + enabled: true + interval: "30s" + labels: + release: prometheus +``` + +其中 `prometheusMonitor` 字段用于配置 Prometheus 监控。 +::: + +## 导入 Grafana Dashboard + +目前 GreptimeDB 集群可使用如下 3 个 Grafana Dashboard 来配置监控面板: + +- [集群指标 Dashboard](https://github.com/GreptimeTeam/greptimedb/blob/main/grafana/greptimedb-cluster.json) +- [集群日志 Dashboard](https://github.com/GreptimeTeam/helm-charts/blob/main/charts/greptimedb-cluster/dashboards/greptimedb-cluster-logs.json) +- [慢查询日志 Dashboard](https://github.com/GreptimeTeam/helm-charts/blob/main/charts/greptimedb-cluster/dashboards/greptimedb-cluster-slow-queries.json) + + +:::note +其中 **集群日志 Dashboard** 和 **慢查询日志 Dashboard** 仅适用于自监控模式,而 **集群指标 Dashboard** 则适用于自监控模式和 Prometheus 监控模式。 +::: + +如果你使用 Helm Chart 部署 GreptimeDB 集群,你可以通过启用 `grafana.enabled` 来一键部署 Grafana 实例,并导入相应的 Dashboard(可参考[立即开始](../getting-started.md)),如下所示: + +```yaml +grafana: + enabled: true +``` + +如果你是已经部署了 Grafana 实例,你可以参考如下步骤来导入相应的 Dashboard: + +1. **添加相应的 Data Sources** + + 你可以参考 Grafana 官方文档的 [datasources](https://grafana.com/docs/grafana/latest/datasources/) 来添加如下 3 个数据源: + + - **`metrics` 数据源** + + 用于导入集群的 Prometheus 监控数据,适用于自监控模式和 Prometheus 监控模式。如上文所述,当使用自监控模式时,此时可使使用 `http://${cluster}-monitor-standalone.${namespace}.svc.cluster.local:4000/v1/prometheus` 作为数据源的 URL。如果使用 Prometheus 监控模式,用户可根据具体 Prometheus 实例的 URL 来配置数据源。 + + - **`information-schema` 数据源** + + 这部分数据源用于使用 SQL 协议导入集群内部的元数据信息,适用于自监控模式和 Prometheus 监控模式。此时我们可以用 `${cluster}-frontend.${namespace}.svc.cluster.local:4002` 作为 SQL 协议的地址,并使用 `information_schema` 作为数据库名称进行连接。 + + - **`logs` 数据源** + + 这部分数据源用于使用 SQL 协议导入集群的日志和慢查询日志,**仅适用于自监控模式**。此时我们可以用 `${cluster}-monitor-standalone.${namespace}.svc.cluster.local:4002` 作为 SQL 协议的地址,并使用 `public` 作为数据库名称进行连接。 + + +2. **导入相应的 Dashboard** + + 你可以参考 Grafana 官方文档的 [Import dashboards](https://grafana.com/docs/grafana/latest/dashboards/build-dashboards/import-dashboards/) 来导入相应的 Dashboard。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/deployments/deploy-on-kubernetes/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/deployments/deploy-on-kubernetes/overview.md new file mode 100644 index 000000000..47cd1a66c --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/deployments/deploy-on-kubernetes/overview.md @@ -0,0 +1,28 @@ +--- +keywords: [Kubernetes 部署, Operator 模式, 自动化管理, 集群部署, 单机实例, 私有云, 公有云] +description: 在 Kubernetes 上部署 GreptimeDB 的概述,介绍了 GreptimeDB Operator 的功能和使用方法。 +--- + +# 概述 + +## GreptimeDB on Kubernetes + +GreptimeDB 是专为云原生环境而设计的时序数据库,自诞生以来就支持在 Kubernetes 上部署。我们提供了一个 [GreptimeDB Operator](https://github.com/GrepTimeTeam/greptimedb-operator) 来管理 GreptimeDB 在 Kubernetes 上的部署、配置和扩容。基于 GreptimeDB Operator,你可以很轻松地部署、升级和管理 GreptimeDB 集群和单机实例。无论是私有还是公有云部署,GreptimeDB Operator 都将快速部署和扩容 GreptimeDB 变得简单易行。 + +我们**强烈建议**使用 GreptimeDB Operator 在 Kubernetes 上部署 GreptimeDB。 + +## 立即开始 + +你可以将 [立即开始](./getting-started.md) 作为你的第一篇指南以了解整体情况。在该指南中,我们提供了用于在 Kubernetes 上部署 GreptimeDB 集群的完整过程。 + +## GreptimeDB Operator + +- [GreptimeDB Operator 管理](./greptimedb-operator-management.md) + +## 监控 + +- [集群监控部署](./monitoring/cluster-monitoring-deployment.md) + +## 配置 + +- [常见 Helm Chart 配置项](./common-helm-chart-configurations.md) diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/deployments/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/deployments/overview.md new file mode 100644 index 000000000..1bdb83243 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/deployments/overview.md @@ -0,0 +1,35 @@ +--- +keywords: [配置项, 鉴权, Kubernetes 部署, Android 运行, 容量规划, GreptimeCloud] +description: GreptimeDB 部署概述,包括配置项、鉴权、在 Kubernetes 上部署、在 Android 上运行、容量规划和 GreptimeCloud 的介绍。 +--- + +# 概述 + +## 配置项 + +在部署 GreptimeDB 之前,你需要[配置服务器](configuration.md)以满足需求, +其中包括设置协议选项、存储选项等。 + +## 鉴权 + +GreptimeDB 默认不启用鉴权认证。 +了解如何为你的部署手动[配置鉴权](./authentication/overview.md)。 + +## 部署到 Kubernetes + +[在 Kubernetes 集群上部署 GreptimeDB](./deploy-on-kubernetes/overview.md)的逐步说明。 + +## 在 Android 上运行 + +[在 Android 设备上运行 GreptimeDB](run-on-android.md)的指南。 + +## 容量规划 + +了解如何[规划容量](/user-guide/administration/capacity-plan.md)以确保你的 GreptimeDB 部署能够处理你的工作负载。 + +## GreptimeCloud + +比起管理自己的 GreptimeDB 集群, +你可以使用 [GreptimeCloud](https://greptime.cloud) 来管理 GreptimeDB 实例、监控指标和设置警报。 +GreptimeCloud 是由完全托管的无服务器 GreptimeDB 提供支持的云服务,为时间序列数据平台和 Prometheus 后端提供了可扩展和高效的解决方案。 +有关更多信息,请参阅[GreptimeCloud 文档](https://docs.greptime.cn/nightly/greptimecloud/overview)。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/user-guide/operations/run-on-android.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/deployments/run-on-android.md similarity index 91% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7/user-guide/operations/run-on-android.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/deployments/run-on-android.md index e6c65ae58..6d6cabdf7 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/user-guide/operations/run-on-android.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/deployments/run-on-android.md @@ -1,3 +1,8 @@ +--- +keywords: [安卓平台, ARM64 CPU, Android API 23, Termux 终端模拟器, 二进制文件, 配置文件, 启动服务, 连接数据库] +description: 在安卓平台运行 GreptimeDB 的指南,包括安装终端模拟器、下载二进制文件、创建配置文件、启动服务和连接数据库的步骤。 +--- + # 在安卓平台运行 从 v0.4.0 开始,GreptimeDB 支持在采用了 ARM64 CPU 和 Android API 23 版本以上的安卓平台运行。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/flow-computation/continuous-aggregation.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/flow-computation/continuous-aggregation.md new file mode 100644 index 000000000..4cb932890 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/flow-computation/continuous-aggregation.md @@ -0,0 +1,385 @@ +--- +keywords: [持续聚合, 实时分析, 实时监控, 实时仪表盘, 聚合函数, 时间窗口, SQL 示例] +description: 持续聚合是处理时间序列数据以提供实时洞察的关键方面。本文介绍了持续聚合的三个主要用例:实时分析、实时监控和实时仪表盘,并提供了详细的 SQL 示例。 +--- + +# 持续聚合 + +持续聚合是处理时间序列数据以提供实时洞察的关键方面。 +Flow 引擎使开发人员能够无缝地执行持续聚合,例如计算总和、平均值和其他指标。 +它在指定的时间窗口内高效地更新聚合数据,使其成为分析的宝贵工具。 + +持续聚合的三个主要用例示例如下: + +1. **实时分析**:一个实时分析平台,不断聚合来自事件流的数据,提供即时洞察,同时可选择将数据降采样到较低分辨率。例如,此系统可以编译来自高频日志事件流(例如,每毫秒发生一次)的数据,以提供每分钟的请求数、平均响应时间和每分钟的错误率等最新洞察。 +2. **实时监控**:一个实时监控系统,不断聚合来自事件流的数据,根据聚合数据提供实时警报。例如,此系统可以处理来自传感器事件流的数据,以提供当温度超过某个阈值时的实时警报。 +3. **实时仪表盘**:一个实时仪表盘,显示每分钟的请求数、平均响应时间和每分钟的错误数。此仪表板可用于监控系统的健康状况,并检测系统中的任何异常。 + +在所有这些用例中,持续聚合系统不断聚合来自事件流的数据,并根据聚合数据提供实时洞察和警报。系统还可以将数据降采样到较低分辨率,以减少存储和处理的数据量。这使得系统能够提供实时洞察和警报,同时保持较低的数据存储和处理成本。 + +## 实时分析示例 + +### 日志统计 + +这个例子是根据输入表中的数据计算一系列统计数据,包括一分钟时间窗口内的总日志数、最小大小、最大大小、平均大小以及大小大于 550 的数据包数。 + +首先,创建一个 source 表 `ngx_access_log` 和一个 sink 表 `ngx_statistics`,如下所示: + +```sql +CREATE TABLE `ngx_access_log` ( + `client` STRING NULL, + `ua_platform` STRING NULL, + `referer` STRING NULL, + `method` STRING NULL, + `endpoint` STRING NULL, + `trace_id` STRING NULL FULLTEXT, + `protocol` STRING NULL, + `status` SMALLINT UNSIGNED NULL, + `size` DOUBLE NULL, + `agent` STRING NULL, + `access_time` TIMESTAMP(3) NOT NULL, + TIME INDEX (`access_time`) +) +WITH( + append_mode = 'true' +); +``` + +```sql +CREATE TABLE `ngx_statistics` ( + `status` SMALLINT UNSIGNED NULL, + `total_logs` BIGINT NULL, + `min_size` DOUBLE NULL, + `max_size` DOUBLE NULL, + `avg_size` DOUBLE NULL, + `high_size_count` BIGINT NULL, + `time_window` TIMESTAMP time index, + `update_at` TIMESTAMP NULL, + PRIMARY KEY (`status`) +); +``` + +然后创建名为 `ngx_aggregation` 的 flow 任务,包括 `count`、`min`、`max`、`avg` `size` 列的聚合函数,以及大于 550 的所有数据包的大小总和。聚合是在 `access_time` 列的 1 分钟固定窗口中计算的,并且还按 `status` 列分组。因此,你可以实时了解有关数据包大小和对其的操作的信息,例如,如果 `high_size_count` 在某个时间点变得太高,你可以进一步检查是否有任何问题,或者如果 `max_size` 列在 1 分钟时间窗口内突然激增,你可以尝试定位该数据包并进一步检查。 + +```sql +CREATE FLOW ngx_aggregation +SINK TO ngx_statistics +AS +SELECT + status, + count(client) AS total_logs, + min(size) as min_size, + max(size) as max_size, + avg(size) as avg_size, + sum(case when `size` > 550 then 1 else 0 end) as high_size_count, + date_bin(INTERVAL '1 minutes', access_time) as time_window, +FROM ngx_access_log +GROUP BY + status, + time_window; +``` + +要检查持续聚合是否正常工作,首先插入一些数据到源表 `ngx_access_log` 中。 + +```sql +INSERT INTO ngx_access_log +VALUES + ("android", "Android", "referer", "GET", "/api/v1", "trace_id", "HTTP", 200, 1000, "agent", "2021-07-01 00:00:01.000"), + ("ios", "iOS", "referer", "GET", "/api/v1", "trace_id", "HTTP", 200, 500, "agent", "2021-07-01 00:00:30.500"), + ("android", "Android", "referer", "GET", "/api/v1", "trace_id", "HTTP", 200, 600, "agent", "2021-07-01 00:01:01.000"), + ("ios", "iOS", "referer", "GET", "/api/v1", "trace_id", "HTTP", 404, 700, "agent", "2021-07-01 00:01:01.500"); +``` + +则 `ngx_access_log` 表将被增量更新以包含以下数据: + +```sql +SELECT * FROM ngx_statistics; +``` + +```sql + status | total_logs | min_size | max_size | avg_size | high_size_count | time_window | update_at +--------+------------+----------+----------+----------+-----------------+----------------------------+---------------------------- + 200 | 2 | 500 | 1000 | 750 | 1 | 2021-07-01 00:00:00.000000 | 2024-07-24 08:36:17.439000 + 200 | 1 | 600 | 600 | 600 | 1 | 2021-07-01 00:01:00.000000 | 2024-07-24 08:36:17.439000 + 404 | 1 | 700 | 700 | 700 | 1 | 2021-07-01 00:01:00.000000 | 2024-07-24 08:36:17.439000 +(3 rows) +``` + +尝试向 `ngx_access_log` 表中插入更多数据: + +```sql +INSERT INTO ngx_access_log +VALUES + ("android", "Android", "referer", "GET", "/api/v1", "trace_id", "HTTP", 200, 500, "agent", "2021-07-01 00:01:01.000"), + ("ios", "iOS", "referer", "GET", "/api/v1", "trace_id", "HTTP", 404, 800, "agent", "2021-07-01 00:01:01.500"); +``` + +结果表 `ngx_statistics` 将被增量更新,注意 `max_size`、`avg_size` 和 `high_size_count` 是如何更新的: + +```sql +SELECT * FROM ngx_statistics; +``` + +```sql + status | total_logs | min_size | max_size | avg_size | high_size_count | time_window | update_at +--------+------------+----------+----------+----------+-----------------+----------------------------+---------------------------- + 200 | 2 | 500 | 1000 | 750 | 1 | 2021-07-01 00:00:00.000000 | 2024-07-24 08:36:17.439000 + 200 | 2 | 500 | 600 | 550 | 1 | 2021-07-01 00:01:00.000000 | 2024-07-24 08:36:46.495000 + 404 | 2 | 700 | 800 | 750 | 2 | 2021-07-01 00:01:00.000000 | 2024-07-24 08:36:46.495000 +(3 rows) +``` + +`ngx_statistics` 表中的列解释如下: + +- `status`: HTTP 响应的状态码。 +- `total_logs`: 相同状态码的日志总数。 +- `min_size`: 相同状态码的数据包的最小大小。 +- `max_size`: 相同状态码的数据包的最大大小。 +- `avg_size`: 相同状态码的数据包的平均大小。 +- `high_size_count`: 包大小大于 550 的数据包数。 +- `time_window`: 聚合的时间窗口。 +- `update_at`: 聚合结果更新的时间。 + +### 按时间窗口查询国家 + +另一个实时分析的示例是从 `ngx_access_log` 表中查询所有不同的国家。 +你可以使用以下查询按时间窗口对国家进行分组: + +```sql +/* source 表 */ +CREATE TABLE ngx_access_log ( + client STRING, + country STRING, + access_time TIMESTAMP TIME INDEX, + PRIMARY KEY(client) +); + +/* sink 表 */ +CREATE TABLE ngx_country ( + country STRING, + time_window TIMESTAMP TIME INDEX, + update_at TIMESTAMP, + PRIMARY KEY(country) +); + +/* 创建 flow 任务以计算不同的国家 */ +CREATE FLOW calc_ngx_country +SINK TO ngx_country +AS +SELECT + DISTINCT country, + date_bin(INTERVAL '1 hour', access_time) as time_window, +FROM ngx_access_log +GROUP BY + country, + time_window; +``` + +上述查询将 `ngx_access_log` 表中的数据聚合到 `ngx_country` 表中,它计算了每个时间窗口内的不同国家。 +`date_bin` 函数用于将数据聚合到一小时的间隔中。 +`ngx_country` 表将不断更新聚合数据,以监控访问系统的不同国家。 + +你可以向 source 表 `ngx_access_log` 插入一些数据: + +```sql +INSERT INTO ngx_access_log VALUES + ("client1", "US", "2022-01-01 01:00:00"), + ("client2", "US", "2022-01-01 01:00:00"), + ("client3", "UK", "2022-01-01 01:00:00"), + ("client4", "UK", "2022-01-01 02:00:00"), + ("client5", "CN", "2022-01-01 02:00:00"), + ("client6", "CN", "2022-01-01 02:00:00"), + ("client7", "JP", "2022-01-01 03:00:00"), + ("client8", "JP", "2022-01-01 03:00:00"), + ("client9", "KR", "2022-01-01 03:00:00"), + ("client10", "KR", "2022-01-01 03:00:00"); +``` + +等待一秒钟,让 flow 将结果写入 sink 表,然后查询: + +```sql +select * from ngx_country; +``` + +```sql ++---------+---------------------+----------------------------+ +| country | time_window | update_at | ++---------+---------------------+----------------------------+ +| CN | 2022-01-01 02:00:00 | 2024-10-22 08:17:47.906000 | +| JP | 2022-01-01 03:00:00 | 2024-10-22 08:17:47.906000 | +| KR | 2022-01-01 03:00:00 | 2024-10-22 08:17:47.906000 | +| UK | 2022-01-01 01:00:00 | 2024-10-22 08:17:47.906000 | +| UK | 2022-01-01 02:00:00 | 2024-10-22 08:17:47.906000 | +| US | 2022-01-01 01:00:00 | 2024-10-22 08:17:47.906000 | ++---------+---------------------+----------------------------+ +``` + +## 实时监控示例 + +假设你有一个来自温度传感器网络的传感器事件流,你希望实时监控这些事件。 +传感器事件包含传感器 ID、温度读数、读数的时间戳和传感器的位置等信息。 +你希望不断聚合这些数据,以便在温度超过某个阈值时提供实时告警。持续聚合的查询如下: + +```sql +/* 创建 source 表 */ +CREATE TABLE temp_sensor_data ( + sensor_id INT, + loc STRING, + temperature DOUBLE, + ts TIMESTAMP TIME INDEX +); + +/* 创建 sink 表 */ +CREATE TABLE temp_alerts ( + sensor_id INT, + loc STRING, + max_temp DOUBLE, + time_window TIMESTAMP TIME INDEX, + update_at TIMESTAMP, + PRIMARY KEY(sensor_id, loc) +); + +CREATE FLOW temp_monitoring +SINK TO temp_alerts +AS +SELECT + sensor_id, + loc, + max(temperature) as max_temp, + date_bin(INTERVAL '10 seconds', ts) as time_window, +FROM temp_sensor_data +GROUP BY + sensor_id, + loc, + time_window +HAVING max_temp > 100; +``` + +上述查询将 `temp_sensor_data` 表中的数据不断聚合到 `temp_alerts` 表中。 +它计算每个传感器和位置的最大温度读数,并过滤出最大温度超过 100 度的数据。 +`temp_alerts` 表将不断更新聚合数据, +当温度超过阈值时提供实时警报(即 `temp_alerts` 表中的新行)。 + +现在我们已经创建了 flow 任务,可以向 source 表 `temp_sensor_data` 插入一些数据: + +```sql +INSERT INTO temp_sensor_data VALUES + (1, "room1", 98.5, "2022-01-01 00:00:00"), + (2, "room2", 99.5, "2022-01-01 00:00:01"); +``` + +表现在应该是空的,等待至少一秒钟让 flow 将结果更新到输出表: + +```sql +SELECT * FROM temp_alerts; +``` + +```sql +Empty set (0.00 sec) +``` + +插入一些会触发警报的数据: + +```sql +INSERT INTO temp_sensor_data VALUES + (1, "room1", 101.5, "2022-01-01 00:00:02"), + (2, "room2", 102.5, "2022-01-01 00:00:03"); +``` + +等待至少一秒钟,让 flow 将结果更新到输出表: + +```sql +SELECT * FROM temp_alerts; +``` + +```sql ++-----------+-------+----------+---------------------+----------------------------+ +| sensor_id | loc | max_temp | time_window | update_at | ++-----------+-------+----------+---------------------+----------------------------+ +| 1 | room1 | 101.5 | 2022-01-01 00:00:00 | 2024-10-22 09:13:07.535000 | +| 2 | room2 | 102.5 | 2022-01-01 00:00:00 | 2024-10-22 09:13:07.535000 | ++-----------+-------+----------+---------------------+----------------------------+ +``` + +## 实时仪表盘 + +假设你需要一个条形图来显示每个状态码的包大小分布,以监控系统的健康状况。持续聚合的查询如下: + +```sql +/* 创建 source 表 */ +CREATE TABLE ngx_access_log ( + client STRING, + stat INT, + size INT, + access_time TIMESTAMP TIME INDEX +); +/* 创建 sink 表 */ +CREATE TABLE ngx_distribution ( + stat INT, + bucket_size INT, + total_logs BIGINT, + time_window TIMESTAMP TIME INDEX, + update_at TIMESTAMP, + PRIMARY KEY(stat, bucket_size) +); +/* 创建 flow 任务以计算每个状态码的包大小分布 */ +CREATE FLOW calc_ngx_distribution SINK TO ngx_distribution AS +SELECT + stat, + trunc(size, -1)::INT as bucket_size, + count(client) AS total_logs, + date_bin(INTERVAL '1 minutes', access_time) as time_window, +FROM + ngx_access_log +GROUP BY + stat, + time_window, + bucket_size; +``` + +该查询将 `ngx_access_log` 表中的数据汇总到 `ngx_distribution` 表中。 +它计算每个时间窗口内的状态代码和数据包大小存储桶(存储桶大小为 10,由 `trunc` 指定,第二个参数为 -1)的日志总数。 +`date_bin` 函数将数据分组为一分钟的间隔。 +因此,`ngx_distribution` 表会不断更新, +提供每个状态代码的数据包大小分布的实时洞察。 + +现在我们已经创建了 flow 任务,可以向 source 表 `ngx_access_log` 插入一些数据: + +```sql +INSERT INTO ngx_access_log VALUES + ("cli1", 200, 100, "2022-01-01 00:00:00"), + ("cli2", 200, 104, "2022-01-01 00:00:01"), + ("cli3", 200, 120, "2022-01-01 00:00:02"), + ("cli4", 200, 124, "2022-01-01 00:00:03"), + ("cli5", 200, 140, "2022-01-01 00:00:04"), + ("cli6", 404, 144, "2022-01-01 00:00:05"), + ("cli7", 404, 160, "2022-01-01 00:00:06"), + ("cli8", 404, 164, "2022-01-01 00:00:07"), + ("cli9", 404, 180, "2022-01-01 00:00:08"), + ("cli10", 404, 184, "2022-01-01 00:00:09"); +``` + +等待至少一秒钟,让 flow 将结果更新到 sink 表: + +```sql +SELECT * FROM ngx_distribution; +``` + +```sql ++------+-------------+------------+---------------------+----------------------------+ +| stat | bucket_size | total_logs | time_window | update_at | ++------+-------------+------------+---------------------+----------------------------+ +| 200 | 100 | 2 | 2022-01-01 00:00:00 | 2024-10-22 09:17:09.592000 | +| 200 | 120 | 2 | 2022-01-01 00:00:00 | 2024-10-22 09:17:09.592000 | +| 200 | 140 | 1 | 2022-01-01 00:00:00 | 2024-10-22 09:17:09.592000 | +| 404 | 140 | 1 | 2022-01-01 00:00:00 | 2024-10-22 09:17:09.592000 | +| 404 | 160 | 2 | 2022-01-01 00:00:00 | 2024-10-22 09:17:09.592000 | +| 404 | 180 | 2 | 2022-01-01 00:00:00 | 2024-10-22 09:17:09.592000 | ++------+-------------+------------+---------------------+----------------------------+ +``` + +## 下一步 + +- [管理 Flow](manage-flow.md):深入了解 Flow 引擎的机制和定义 Flow 的 SQL 语法。 +- [表达式](expressions.md):了解 Flow 引擎支持的数据转换表达式。 + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/flow-computation/expressions.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/flow-computation/expressions.md new file mode 100644 index 000000000..a7180deeb --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/flow-computation/expressions.md @@ -0,0 +1,28 @@ +--- +keywords: [聚合函数, 标量函数, count, sum, avg, min, max, date_bin, date_trunc, trunc] +description: 列出了 GreptimeDB 中 flow 支持的聚合函数和标量函数。 +--- + +# 表达式 + +## 聚合函数 + +此处列出了 flow 中所有支持的聚合函数。 + +- `count(column)`: 行数。 +- `sum(column)`: 列的和。 +- `avg(column)`: 列的平均值。 +- `min(column)`: 列的最小值。 +- `max(column)`: 列的最大值。 + +未来将添加更多聚合函数。 + +## Scalar functions + +Flow 支持大多数 datafusion 中的标量函数,有关支持的标量函数的完整列表,请参见[datafusion](/reference/sql/functions/df-functions.md#scalar-functions)。 + +以下是一些 flow 中最常用的标量函数: + +- [`date_bin`](/reference/sql/functions/df-functions.md#date_bin): calculate time intervals and returns the start of the interval nearest to the specified timestamp. +- [`date_trunc`](/reference/sql/functions/df-functions.md#date_trunc): truncate a timestamp value to a specified precision. +- [`trunc`](/reference/sql/functions/df-functions.md#trunc): truncate a number to a whole number or truncated to the specified decimal places. \ No newline at end of file diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/flow-computation/manage-flow.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/flow-computation/manage-flow.md new file mode 100644 index 000000000..343f3334c --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/flow-computation/manage-flow.md @@ -0,0 +1,221 @@ +--- +keywords: [创建 flow, 删除 flow, 输入表, sink 表, SQL 语法, 时间窗口, 刷新 flow] +description: 介绍如何在 GreptimeDB 中创建和删除 flow,包括创建 sink 表、flow 的 SQL 语法和示例。 +--- + +# 管理 Flow + +每一个 `flow` 是 GreptimeDB 中的一个持续聚合查询。 +它根据传入的数据持续更新并聚合数据。 +本文档描述了如何创建和删除一个 flow。 + +## 创建输入表 + +在创建 `flow` 之前,你需要先创建一张输入表来存储原始的输入数据,比如: +```sql +CREATE TABLE temp_sensor_data ( + sensor_id INT, + loc STRING, + temperature DOUBLE, + ts TIMESTAMP TIME INDEX, + PRIMARY KEY(sensor_id, loc) +); +``` +但是如果你不想存储输入数据,可以在创建输入表时设置表选项 `WITH ('ttl' = 'instant')` 如下: +```sql +CREATE TABLE temp_sensor_data ( + sensor_id INT, + loc STRING, + temperature DOUBLE, + ts TIMESTAMP TIME INDEX, + PRIMARY KEY(sensor_id, loc) +) WITH ('ttl' = 'instant'); +``` + +将 `ttl` 设置为 `'instant'` 会使得输入表成为一张临时的表,也就是说它会自动丢弃一切插入的数据,而表本身一直会是空的,插入数据只会被送到 `flow` 任务处用作计算用途。 + +## 创建 sink 表 + +在创建 flow 之前,你需要有一个 sink 表来存储 flow 生成的聚合数据。 +虽然它与常规的时间序列表相同,但有一些重要的注意事项: + +- **列的顺序和类型**:确保 sink 表中列的顺序和类型与 flow 查询结果匹配。 +- **时间索引**:为 sink 表指定 `TIME INDEX`,通常使用时间窗口函数生成的时间列。 +- **更新时间**:Flow 引擎会自动将更新时间附加到每个计算结果行的末尾。此更新时间存储在 `updated_at` 列中。请确保在 sink 表的 schema 中包含此列。 +- **Tag**:使用 `PRIMARY KEY` 指定 Tag,与 time index 一起作为行数据的唯一标识,并优化查询性能。 + +例如: + +```sql +/* 创建 sink 表 */ +CREATE TABLE temp_alerts ( + sensor_id INT, + loc STRING, + max_temp DOUBLE, + time_window TIMESTAMP TIME INDEX, + update_at TIMESTAMP, + PRIMARY KEY(sensor_id, loc) +); + +CREATE FLOW temp_monitoring +SINK TO temp_alerts +AS +SELECT + sensor_id, + loc, + max(temperature) AS max_temp, + date_bin(INTERVAL '10 seconds', ts) AS time_window +FROM temp_sensor_data +GROUP BY + sensor_id, + loc, + time_window +HAVING max_temp > 100; +``` + +sink 表包含列 `sensor_id`、`loc`、`max_temp`、`time_window` 和 `update_at`。 + +- 前四列分别对应 flow 的查询结果列 `sensor_id`、`loc`、`max(temperature)` 和 `date_bin(INTERVAL '10 seconds', ts)`。 +- `time_window` 列被指定为 sink 表的 `TIME INDEX`。 +- `update_at` 列是 schema 中的最后一列,用于存储数据的更新时间。 +- 最后的 `PRIMARY KEY` 指定 `sensor_id` 和 `loc` 作为 Tag 列。 + 这意味着 flow 将根据 Tag `sensor_id` 和 `loc` 以及时间索引 `time_window` 插入或更新数据。 + +## 创建 flow + +创建 flow 的语法是: + +```sql +CREATE [ OR REPLACE ] FLOW [ IF NOT EXISTS ] +SINK TO +[ EXPIRE AFTER ] +[ COMMENT '' ] +AS +; +``` + +当指定 `OR REPLACE` 时,如果已经存在同名的 flow,它将被更新为新 flow。请注意,这仅影响 flow 任务本身,source 表和 sink 表将不会被更改。当指定 `IF NOT EXISTS` 时,如果 flow 已经存在,它将不执行任何操作,而不是报告错误。还需要注意的是,`OR REPLACE` 不能与 `IF NOT EXISTS` 一起使用。 + +- `flow-name` 是目录级别的唯一标识符。 +- `sink-table-name` 是存储聚合数据的表名。 + 它可以是一个现有的表或一个新表。如果目标表不存在,`flow` 将创建目标表。 + +- `EXPIRE AFTER` 是一个可选的时间间隔,用于从 Flow 引擎中过期数据。 + 有关更多详细信息,请参考 [`EXPIRE AFTER`](#expire-after-语句) 部分。 +- `COMMENT` 是 flow 的描述。 +- `SQL` 部分定义了用于持续聚合的查询。 + 它定义了为 flow 提供数据的源表。 + 每个 flow 可以有多个源表。 + 有关详细信息,请参考[编写查询](#编写-sql-查询) 部分。 + +一个创建 flow 的简单示例: + +```sql +CREATE FLOW IF NOT EXISTS my_flow +SINK TO my_sink_table +EXPIRE AFTER INTERVAL '1 hour' +COMMENT 'My first flow in GreptimeDB' +AS +SELECT + max(temperature) as max_temp, + date_bin(INTERVAL '10 seconds', ts) as time_window, +FROM temp_sensor_data +GROUP BY time_window; +``` + +创建的 flow 将每 10 秒计算一次 `max(temperature)` 并将结果存储在 `my_sink_table` 中。 +所有在 1 小时内的数据都将用于 flow 计算。 + +### `EXPIRE AFTER` 子句 + +`EXPIRE AFTER` 子句指定数据将在 flow 引擎中过期的时间间隔。 +此过期仅影响 flow 引擎中的数据,不影响 source 表中的数据。 + +当 flow 引擎处理聚合操作(`update_at` 时间)时, +时间索引早于指定间隔的数据将过期。 + +例如,如果 flow 引擎在 10:00:00 处理聚合,并且设置了 `INTERVAL '1 hour'`, +则早于 09:00:00 的数据将过期。 +只有从 09:00:00 开始的数据将用于聚合。 + +### 编写 SQL 查询 + +flow 的 `SQL` 部分类似于标准的 `SELECT` 子句,但有一些不同之处。查询的语法如下: + +```sql +SELECT AGGR_FUNCTION(column1, column2,..) [, TIME_WINDOW_FUNCTION() as time_window] FROM GROUP BY {time_window | column1, column2,.. }; +``` + +在 `SELECT` 关键字之后只允许以下类型的表达式: +- 聚合函数:有关详细信息,请参阅[表达式](./expressions.md)文档。 +- 时间窗口函数:有关详细信息,请参阅[定义时间窗口](#define-time-window)部分。 +- 标量函数:例如 `col`、`to_lowercase(col)`、`col + 1` 等。这部分与 GreptimeDB 中的标准 `SELECT` 子句相同。 + +查询语法中的其他部分需要注意以下几点: +- 必须包含一个 `FROM` 子句以指定 source 表。由于目前不支持 join 子句,因此只能聚合来自单个表的列。 +- 支持 `WHERE` 和 `HAVING` 子句。`WHERE` 子句在聚合之前过滤数据,而 `HAVING` 子句在聚合之后过滤数据。 +- `DISTINCT` 目前仅适用于 `SELECT DISTINCT column1 ..` 语法。它用于从结果集中删除重复行。`SELECT count(DISTINCT column1) ...` 尚不可用,但将来会添加。 +- `GROUP BY` 子句的工作方式与标准查询相同,即按指定列对数据进行分组,在其中指定时间窗口列对于持续聚合场景至关重要。 + `GROUP BY` 中的其他表达式可以是 literal、列名或 scalar 表达式。 +- 不支持`ORDER BY`、`LIMIT` 和 `OFFSET`。 + +有关如何在实时分析、监控和仪表板中使用持续聚合的更多示例,请参阅[持续聚合](./continuous-aggregation.md)。 + +### 定义时间窗口 + +时间窗口是持续聚合查询的重要属性。 +它定义了数据在流中的聚合方式。 +这些窗口是左闭右开的区间。 + +时间窗口对应于时间范围。 +source 表中的数据将根据时间索引列映射到相应的窗口。 +时间窗口也是聚合表达式计算的范围,因此每个时间窗口将在结果表中生成一行。 + +你可以在 `SELECT` 关键字之后使用 `date_bin()` 来定义固定的时间窗口。 +例如: + +```sql +SELECT + max(temperature) as max_temp, + date_bin(INTERVAL '10 seconds', ts) as time_window +FROM temp_sensor_data +GROUP BY time_window; +``` + +在此示例中,`date_bin(INTERVAL '10 seconds', ts)` 函数创建从 UTC 00:00:00 开始的 10 秒时间窗口。 +`max(temperature)` 函数计算每个时间窗口内的最大温度值。 + +有关该函数行为的更多详细信息, +请参阅 [`date_bin`](/reference/sql/functions/df-functions.md#date_bin)。 + +:::tip 提示 +目前,flow 的内部状态(例如记录当前计数的 `count(col)` 的累加值)没有持久存储。 +为了在内部状态故障时尽量减少数据丢失,建议使用较小的时间窗口。 + +这种内部状态丢失不会影响 sink 表中的现有数据。 +::: + +## 刷新 flow + +当 source 表中有新数据到达时,flow 引擎会在 1 秒内自动处理聚合操作。 +但你依然可以使用 `ADMIN FLUSH_FLOW` 命令手动触发 flow 引擎立即执行聚合操作。 + +```sql +ADMIN FLUSH_FLOW('') +``` + +## 删除 flow + +请使用以下 `DROP FLOW` 子句删除 flow: + +To delete a flow, use the following `DROP FLOW` clause: + +```sql +DROP FLOW [IF EXISTS] +``` + +例如: + +```sql +DROP FLOW IF EXISTS my_flow; +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/flow-computation/overview.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/flow-computation/overview.md new file mode 100644 index 000000000..768dc1944 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/flow-computation/overview.md @@ -0,0 +1,125 @@ +--- +keywords: [Flow 引擎, 实时计算, ETL 过程, 即时计算, 程序模型, 使用案例, 快速入门] +description: 了解 GreptimeDB 的 Flow 引擎如何实现数据流的实时计算,如何用于 ETL 过程和即时计算。了解其程序模型、使用案例以及从 nginx 日志计算 user_agent 统计信息的快速入门示例。 +--- + +# 概述 + +GreptimeDB 的 Flow 引擎实现了数据流的实时计算。 +它特别适用于提取-转换-加载 (ETL) 过程或执行即时的过滤、计算和查询,例如求和、平均值和其他聚合。 +Flow 引擎确保数据被增量和连续地处理, +根据到达的新的流数据更新最终结果。 +你可以将其视为一个聪明的物化视图, +它知道何时更新结果视图表以及如何以最小的努力更新它。 + +使用案例包括: + +- 降采样数据点,使用如平均池化等方法减少存储和分析的数据量 +- 提供近实时分析、可操作的信息 + +## 程序模型 + +在将数据插入 source 表后, +数据会同时被写入到 Flow 引擎中。 +在每个触发间隔(一秒)时, +Flow 引擎执行指定的计算并将结果更新到 sink 表中。 +source 表和 sink 表都是 GreptimeDB 中的时间序列表。 +在创建 Flow 之前, +定义这些表的 schema 并设计 Flow 以指定计算逻辑是至关重要的。 +此过程在下图中直观地表示: + +![连续聚合](/flow-ani.svg) + +## 快速入门示例 + +为了说明 GreptimeDB 的 Flow 引擎的功能, +考虑从 nginx 日志计算 user_agent 统计信息的任务。 +source 表是 `nginx_access_log`, +sink 表是 `user_agent_statistics`。 + +首先,创建 source 表 `nginx_access_log`。 +为了优化计算 `user_agent` 字段的性能, +使用 `PRIMARY KEY` 关键字将其指定为 `TAG` 列类型。 + +```sql +CREATE TABLE ngx_access_log ( + ip_address STRING, + http_method STRING, + request STRING, + status_code INT16, + body_bytes_sent INT32, + user_agent STRING, + response_size INT32, + ts TIMESTAMP TIME INDEX, + PRIMARY KEY (ip_address, http_method, user_agent, status_code) +) WITH ('append_mode'='true'); +``` + +接下来,创建 sink 表 `user_agent_statistics`。 +`update_at` 列跟踪数据的最后更新时间,由 Flow 引擎自动更新。 +尽管 GreptimeDB 中的所有表都是时间序列表,但此计算不需要时间窗口。 +因此增加了 `__ts_placeholder` 列作为时间索引占位列。 + +```sql +CREATE TABLE user_agent_statistics ( + user_agent STRING, + total_count INT64, + update_at TIMESTAMP, + __ts_placeholder TIMESTAMP TIME INDEX, + PRIMARY KEY (user_agent) +); +``` + +最后,创建 Flow `user_agent_flow` 以计算 `nginx_access_log` 表中每个 user_agent 的出现次数。 + +```sql +CREATE FLOW user_agent_flow +SINK TO user_agent_statistics +AS +SELECT + user_agent, + COUNT(user_agent) AS total_count +FROM + ngx_access_log +GROUP BY + user_agent; +``` + +一旦创建了 Flow, +Flow 引擎将持续处理 `nginx_access_log` 表中的数据,并使用计算结果更新 `user_agent_statistics` 表。 + +要观察 Flow 的结果, +将示例数据插入 `nginx_access_log` 表。 + +```sql +INSERT INTO ngx_access_log +VALUES + ('192.168.1.1', 'GET', '/index.html', 200, 512, 'Mozilla/5.0', 1024, '2023-10-01T10:00:00Z'), + ('192.168.1.2', 'POST', '/submit', 201, 256, 'curl/7.68.0', 512, '2023-10-01T10:01:00Z'), + ('192.168.1.1', 'GET', '/about.html', 200, 128, 'Mozilla/5.0', 256, '2023-10-01T10:02:00Z'), + ('192.168.1.3', 'GET', '/contact', 404, 64, 'curl/7.68.0', 128, '2023-10-01T10:03:00Z'); +``` + +插入数据后, +查询 `user_agent_statistics` 表以查看结果。 + +```sql +SELECT * FROM user_agent_statistics; +``` + +查询结果将显示 `user_agent_statistics` 表中每个 user_agent 的总数。 + +```sql ++-------------+-------------+----------------------------+---------------------+ +| user_agent | total_count | update_at | __ts_placeholder | ++-------------+-------------+----------------------------+---------------------+ +| Mozilla/5.0 | 2 | 2024-12-12 06:45:33.228000 | 1970-01-01 00:00:00 | +| curl/7.68.0 | 2 | 2024-12-12 06:45:33.228000 | 1970-01-01 00:00:00 | ++-------------+-------------+----------------------------+---------------------+ +``` + +## 下一步 + +- [持续聚合](./continuous-aggregation.md):探索时间序列数据处理中的主要场景,了解持续聚合的三种常见使用案例。 +- [管理 Flow](manage-flow.md):深入了解 Flow 引擎的机制和定义 Flow 的 SQL 语法。 +- [表达式](expressions.md):了解 Flow 引擎支持的数据转换表达式。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/ingest-data/for-iot/emqx.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/ingest-data/for-iot/emqx.md new file mode 100644 index 000000000..0faab5416 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/ingest-data/for-iot/emqx.md @@ -0,0 +1,10 @@ +--- +keywords: [EMQX, MQTT 消息服务器, 物联网, 实时通信, 数据集成, 数据桥接] +description: EMQX 是一款开源的大规模分布式 MQTT 消息服务器,专为物联网和实时通信应用而设计。了解如何将 GreptimeDB 集成到 EMQX 中。 +--- + +# EMQX + +[EMQX](https://www.emqx.io/) 是一款开源的大规模分布式 MQTT 消息服务器,专为物联网和实时通信应用而设计。EMQX 支持多种协议,包括 MQTT (3.1、3.1.1 和 5.0)、HTTP、QUIC 和 WebSocket 等,保证各种网络环境和硬件设备的可访问性。 + +GreptimeDB 可以作为 EMQX 的数据系统。请参考[将 MQTT 数据写入 GreptimeDB](https://docs.emqx.com/zh/emqx/latest/data-integration/data-bridge-greptimedb.html) 了解如何将 GreptimeDB 集成到 EMQX 中。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/user-guide/client-libraries/go.md b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/ingest-data/for-iot/grpc-sdks/go.md similarity index 60% rename from i18n/zh/docusaurus-plugin-content-docs/version-0.7/user-guide/client-libraries/go.md rename to i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/ingest-data/for-iot/grpc-sdks/go.md index 3996bcd06..803e45f43 100644 --- a/i18n/zh/docusaurus-plugin-content-docs/version-0.7/user-guide/client-libraries/go.md +++ b/i18n/zh/docusaurus-plugin-content-docs/version-0.12/user-guide/ingest-data/for-iot/grpc-sdks/go.md @@ -1,3 +1,8 @@ +--- +keywords: [Go SDK, 数据写入, 安装 SDK, 连接数据库, 插入数据, 调试日志, 并发安全] +description: 介绍如何使用 GreptimeDB 提供的 Go Ingest SDK 写入数据,包括安装、连接、插入数据和调试日志等内容。 +--- + import DocTemplate from './template.md' # Go @@ -10,13 +15,18 @@ GreptimeDB 提供的 Go Ingest SDK 是一个轻量级、并发安全的库,使 +
+ +你可以通过[快速开始 Demo](https://github.com/GreptimeTeam/greptimedb-ingester-go/tree/main/examples) 来了解如何使用 GreptimeDB Go SDK。 + +
使用下方的命令安装 Go Ingest SDK: ```shell -go get -u github.com/GreptimeTeam/greptimedb-ingester-go@v0.5.0 +go get -u github.com/GreptimeTeam/greptimedb-ingester-go@VAR::goSdkVersion ``` 引入到代码中: @@ -24,6 +34,7 @@ go get -u github.com/GreptimeTeam/greptimedb-ingester-go@v0.5.0 ```go import ( greptime "github.com/GreptimeTeam/greptimedb-ingester-go" + ingesterContext "github.com/GreptimeTeam/greptimedb-ingester-go/context" "github.com/GreptimeTeam/greptimedb-ingester-go/table" "github.com/GreptimeTeam/greptimedb-ingester-go/table/types" ) @@ -42,12 +53,38 @@ cfg := greptime.NewConfig("127.0.0.1"). // 如果服务配置了 TLS ,设置 TLS 选项来启用安全连接 // WithInsecure(false). // 设置鉴权信息 + // 如果数据库不需要鉴权,移除 WithAuth 方法即可 WithAuth("username", "password") cli, _ := greptime.NewClient(cfg) ```
+
+ +你可以使用 `ingesterContext` 设置表选项。 +例如设置 `ttl` 选项: + +```go +hints := []*ingesterContext.Hint{ + { + Key: "ttl", + Value: "3d", + }, +} + +ctx, cancel := context.WithTimeout(context.Background(), time.Second*3) +ctx = ingesterContext.New(ctx, ingesterContext.WithHints(hints)) +// 使用 ingesterContext写入数据到 GreptimeDB +// `data` 对象在之后的章节中描述 +resp, err := c.client.Write(ctx, data) +if err != nil { + return err +} +``` + +
+
```go @@ -149,7 +186,7 @@ type CpuMetric struct { } func (CpuMetric) TableName() string { - return "cpu_metric" + return "cpu_metric" } cpuMetrics := []CpuMetric{ @@ -162,26 +199,6 @@ cpuMetrics := []CpuMetric{ } ``` - -
@@ -208,130 +225,65 @@ affected, err := cli.CloseStream(ctx)
-
- -有关更多可运行的代码片段和常用方法的解释,请参阅[示例](https://github.com/GreptimeTeam/greptimedb-ingester-go/tree/main/examples)。 - -
- -
- -- [API 文档](https://pkg.go.dev/github.com/GreptimeTeam/greptimedb-ingester-go) - -
- - - - -
- -使用下方的命令安装 GORM: - -```shell -go get -u gorm.io/gorm -``` - -以 MySQL 为例安装 driver: - -```shell -go get -u gorm.io/driver/mysql -``` - -引入到代码中: - -```go -import ( - "gorm.io/gorm" - "gorm.io/driver/mysql" -) -``` - -
- +
-
+在[低层级 API](#低层级-api) 中, +你可以使用 `AddFieldColumn` 方法将列类型指定为 `types.JSON` 来添加 JSON 列。 +然后使用 `struct` 或 `map` 插入 JSON 数据。 ```go -type Mysql struct { - Host string - Port string - User string - Password string - Database string - - DB *gorm.DB -} - -m := &Mysql{ - Host: "127.0.0.1", - Port: "4002", // MySQL 协议的默认端口 - User: "username", - Password: "password", - Database: "public", +sensorReadings, err := table.New("sensor_readings") +// 此处省略了创建其他列的代码 +// ... +// 将列类型指定为 JSON +sensorReadings.AddFieldColumn("attributes", types.JSON) + +// 使用 struct 插入 JSON 数据 +type Attributes struct { + Location string `json:"location"` + Action string `json:"action"` } +attributes := Attributes{ Location: "factory-1" } +sensorReadings.AddRow(... , attributes) -dsn := fmt.Sprintf("tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", - m.Host, m.Port, m.Database) -dsn = fmt.Sprintf("%s:%s@%s", m.User, m.Password, dsn) -db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{}) -if err != nil { - // 错误处理 -} -m.DB = db +// 以下省略了写入数据的代码 +// ... ``` -
- -
-下方的代码声明了一个 GORM 对象模型: +在[高层级 API](#高层级-api) 中,你可以使用 `greptime:"field;column:details;type:json"` 标签将列类型指定为 JSON。 ```go -type CpuMetric struct { - Host string `gorm:"column:host;primaryKey"` - Ts time.Time `gorm:"column:ts;primaryKey"` - CpuUser float64 `gorm:"column:cpu_user"` - CpuSys float64 `gorm:"column:cpu_sys"` +type SensorReadings struct { + // 此处省略了创建其他列的代码 + // ... + // 将列类型指定为 JSON + Attributes string `greptime:"field;column:details;type:json"` + // ... } -``` - -如果你正在使用 [ORM API](#orm-api) 来插入数据,你可以在模型中同时声明 GORM 和 Greptime 标签。 -```go -type CpuMetric struct { - Host string `gorm:"column:host;primaryKey" greptime:"tag;column:host;type:string"` - Ts time.Time `gorm:"column:ts;primaryKey" greptime:"timestamp;column:ts;type:timestamp;precision:millisecond"` - CpuUser float64 `gorm:"column:cpu_user" greptime:"field;column:cpu_user;type:float64"` - CpuSys float64 `gorm:"column:cpu_sys" greptime:"field;column:cpu_sys;type:float64"` +// 使用 struct 插入 JSON 数据 +type Attributes struct { + Location string `json:"location"` + Action string `json:"action"` } -``` - -声明表名: - -```go -func (CpuMetric) TableName() string { - return "cpu_metric" +attributes := Attributes{ Action: "running" } +sensor := SensorReadings{ + // ... + Attributes: attributes, } -``` - -使用原始 SQL 查询数据: - -```go -var cpuMetric CpuMetric -db.Raw("SELECT * FROM cpu_metric LIMIT 10").Scan(&result) +// 以下省略了写入数据的代码 +// ... ``` +请参考 SDK 仓库中的[示例](https://github.com/GreptimeTeam/greptimedb-ingester-go/tree/main/examples/jsondata) 获取插入 JSON 数据的可执行代码。 +
- +
+ +你可以通过[快速开始 Demo](https://github.com/GreptimeTeam/greptimedb-ingester-java/tree/main/ingester-example/src/main/java/io/greptime) 来了解如何使用 GreptimeDB Java SDK。 + +
+
1. 安装 Java 开发工具包(JDK) @@ -29,7 +40,7 @@ GreptimeDB 提供的 Java ingester SDK 是一个轻量级库,具有以下特 io.greptime ingester-all - 0.7.3 + VAR::javaSdkVersion ``` @@ -69,6 +80,21 @@ GreptimeDB client = GreptimeDB.create(opts);
+
+ +你可以使用 `Context` 设置表选项。 +例如,使用以下代码设置 `ttl` 选项: + +```java +Context ctx = Context.newDefault(); +ctx.withHint("ttl", "3d"); +// 使用 ctx 对象写入数据 +// `cpuMetric` 和 `memMetric` 是定义的数据对象,之后的章节中有详细描述 +CompletableFuture> future = greptimeDB.write(Arrays.asList(cpuMetric, memMetric), WriteOp.Insert, ctx); +``` + +
+
```java @@ -183,35 +209,6 @@ LOG.info("Write result: {}", result);
-
- -#### 更新数据 - -关于更新机制,请参考 [更新数据](/user-guide/write-data/overview.md#更新数据)。 -下方代码首先保存了一行数据,然后使用相同的标签和时间索引来更新特定的行数据。 - -```java -Table cpuMetric = Table.from(myMetricCpuSchema); -// 插入一行数据 -long ts = 1703832681000L; -cpuMetric.addRow("host1", ts, 0.23, 0.12); -Result putResult = greptimeDB.write(cpuMetric).get(); - -// 更新行数据 -Table newCpuMetric = Table.from(myMetricCpuSchema); -// 相同的标签 `host1` -// 相同的时间索引 `1703832681000` -// 新的值:cpu_user = `0.80`, cpu_sys = `0.11` -long ts = 1703832681000L; -myMetricCpuSchema.addRow("host1", ts, 0.80, 0.11); - -// 覆盖现有数据 -CompletableFuture> future = greptimeDB.write(myMetricCpuSchema); -Result result = future.get(); -``` - -
-
@@ -318,172 +315,69 @@ LOG.info("Write result: {}", result);
-
- -#### 更新数据 +
-关于更新机制,请参考 [更新数据](/user-guide/write-data/overview.md#更新数据)。 -下方代码首先保存了一行数据,然后使用相同的标签和时间索引来更新特定的行数据。 +在[低层级 API](#低层级-api) 中, +你可以使用 `addField` 方法将列类型指定为 `DataType.Json` 来添加 JSON 列, +然后使用 Map 对象添加 JSON 数据。 ```java -Cpu cpu = new Cpu(); -cpu.setHost("host1"); -cpu.setTs(1703832681000L); -cpu.setCpuUser(0.23); -cpu.setCpuSys(0.12); - -// 插入一行数据 -Result putResult = greptimeDB.writePOJOs(cpu).get(); - -// 更新该行数据 -Cpu newCpu = new Cpu(); -// 相同的标签 `host1` -newCpu.setHost("host1"); -// 相同的时间索引 `1703832681000` -newCpu.setTs(1703832681000L); -// 新的值: cpu_user = `0.80`, cpu_sys = `0.11` -cpu.setCpuUser(0.80); -cpu.setCpuSys(0.11); - -// 覆盖现有数据 -Result updateResult = greptimeDB.writePOJOs(newCpu).get(); -``` - -请参考[此处](https://github.com/GreptimeTeam/greptimedb-ingester-java/tree/main/ingester-example/src/main/java/io/greptime)获取更多代码示例。 - -
- - -
- -### 调试日志 - -ingester SDK 提供了用于调试的指标和日志。 -请参考 [Metrics & Display](https://github.com/GreptimeTeam/greptimedb-ingester-java/blob/main/docs/metrics-display.md) 和 [Magic Tools](https://github.com/GreptimeTeam/greptimedb-ingester-java/blob/main/docs/magic-tools.md) 了解如何启用或禁用日志。 - -
- -
- -请参考[示例](https://github.com/GreptimeTeam/greptimedb-ingester-java/tree/main/ingester-example/src/main/java/io/greptime)获取更多完全可运行的代码片段和常用方法的解释。 - -
- -
- -- [API 文档](https://javadoc.io/doc/io.greptime/ingester-protocol/latest/index.html) - -
- - +// 为 sensor_readings 表构建表结构 +TableSchema sensorReadings = TableSchema.newBuilder("sensor_readings") + // 此处省略了创建其他列的代码 + // ... + // 将列类型指定为 JSON + .addField("attributes", DataType.Json) + .build(); -
+// ... +// 使用 map 添加 JSON 数据 +Map attr = new HashMap<>(); +attr.put("location", "factory-1"); +sensorReadings.addRow(... , attr); -如果你使用的是 [Maven](https://maven.apache.org/),请将以下内容添加到 pom.xml 的依赖项列表中: - -```xml - - - mysql - mysql-connector-java - 8.0.33 - +// 以下省略了写入数据的代码 +// ... ``` -
- -
- -这里我们使用 MySQL 作为示例来演示如何连接到 GreptimeDB。 +在[高层级 API](#高层级-api) 中,你可以在 POJO 对象中指定列类型为 `DataType.Json`。 ```java - -public static Connection getConnection() throws IOException, ClassNotFoundException, SQLException { - Properties prop = new Properties(); - prop.load(QueryJDBC.class.getResourceAsStream("/db-connection.properties")); - - String dbName = (String) prop.get("db.database-driver"); - - String dbConnUrl = (String) prop.get("db.url"); - String dbUserName = (String) prop.get("db.username"); - String dbPassword = (String) prop.get("db.password"); - - Class.forName(dbName); - Connection dbConn = DriverManager.getConnection(dbConnUrl, dbUserName, dbPassword); - - return Objects.requireNonNull(dbConn, "Failed to make connection!"); +@Metric(name = "sensor_readings") +public class Sensor { + // 此处省略了创建其他列的代码 + // ... + // 将列类型指定为 JSON + @Column(name = "attributes", dataType = DataType.Json) + private Map attributes; + // ... } -``` - -你需要一个 properties 文件来存储数据库连接信息,将其放在 Resources 目录中并命名为 `db-connection.properties`。文件内容如下: +Sensor sensor = new Sensor(); +// ... +// 使用 map 添加 JSON 数据 +Map attr = new HashMap<>(); +attr.put("action", "running"); +sensor.setAttributes(attr); -```txt -# DataSource -db.database-driver=com.mysql.cj.jdbc.Driver -db.url=jdbc:mysql://localhost:4002/public -db.username= -db.password= +// 以下省略了写入数据的代码 +// ... ``` -或者你可以从[这里](https://github.com/GreptimeTeam/greptimedb-ingester-java/blob/main/ingester-example/src/main/resources/db-connection.properties)获取文件。 -
-
+
-```java -try (Connection conn = getConnection()) { - Statement statement = conn.createStatement(); - - // DESC table; - ResultSet rs = statement.executeQuery("DESC cpu_metric"); - LOG.info("Column | Type | Key | Null | Default | Semantic Type "); - while (rs.next()) { - LOG.info("{} | {} | {} | {} | {} | {}", - rs.getString(1), - rs.getString(2), - rs.getString(3), - rs.getString(4), - rs.getString(5), - rs.getString(6)); - } - - // SELECT COUNT(*) FROM cpu_metric; - rs = statement.executeQuery("SELECT COUNT(*) FROM cpu_metric"); - while (rs.next()) { - LOG.info("Count: {}", rs.getInt(1)); - } - - // SELECT * FROM cpu_metric ORDER BY ts DESC LIMIT 5; - rs = statement.executeQuery("SELECT * FROM cpu_metric ORDER BY ts DESC LIMIT 5"); - LOG.info("host | ts | cpu_user | cpu_sys"); - while (rs.next()) { - LOG.info("{} | {} | {} | {}", - rs.getString("host"), - rs.getTimestamp("ts"), - rs.getDouble("cpu_user"), - rs.getDouble("cpu_sys")); - } -} +## 调试日志 -``` - -请参考[此处](https://github.com/GreptimeTeam/greptimedb-ingester-java/blob/main/ingester-example/src/main/java/io/greptime/QueryJDBC.java)获取更多可执行代码。 +Java SDK 提供了用于调试的指标和日志。 +请参考 [Metrics & Display](https://github.com/GreptimeTeam/greptimedb-ingester-java/blob/main/docs/metrics-display.md) 和 [Magic Tools](https://github.com/GreptimeTeam/greptimedb-ingester-java/blob/main/docs/magic-tools.md) 了解如何启用或禁用日志。
-